Вы находитесь на странице: 1из 290

http://www.rogerdarlington.me.uk/stories.

htm
l

Fundamentals of Programming
(FOP)
2610001

Introduction to programming& Basics of C:


Concepts of Algorithm and Flowcharts, Process of compilation, Generation of
languages, Basic features of C Language like Identifier, Keywords, Variable, data
types, Operators and Expression. Basic screen and keyboard I/O
9 Lect.
2. Control Statements:
Test Conditions, Conditional execution and selection, Iteration and Repetitive
Executions, Nested loops.
3 Lect.
3. Arrays:
Introduction to contiguous data types. One dimensional arrays, multidimensional
arrays, Array as strings, multidimensional character arrays. Operations on strings.
4 Lect.
4. Functions:
Concept of modular programming, Using functions, Scope of data, Recursive
functions. Command line arguments.
3 Lect.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

5. Pointers:
Need of pointer, Types and uses of pointer, Array and Pointers, Pointers and
strings,
Pointer to Pointer, Pointers and functions, other aspect of pointers.
8 Lect.
6. User Defined Data Types:
Introduction to structures, usage of structure, nested structures, Union and its
usage,
Enumeration types, bit fields.
6 Lect.
7. Files:
Types of files, working with files, usage of file management functions.
8 Lect.
8. Linked List:
Introduction to dynamic memory allocation, singly link list, operations on singly
link list.
6 Lect.
9. Other features of C:
Bitwise operators and its usage, C Preprocessor statements.
3 Lect.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

Books
Text Book:
1. Programming in C, by Pradip Dey & Manas Ghosh, Publisher Oxford
Reference Books:
1. Programming in ANSI C, by Balagurusamy, Publisher - Tata McGraw Hill.
2. Computer Science: A Structured Programming Approach Using C, by
Behrouz A. Forouzan & Richard F. Gilberg, Publisher Thomson
Education.
3. Programming with ANSI and Turbo C, by Ashok N Kamthane, Publisher
Pearson Education.
4. Mastering C, by Venugopal & Prasad, Publisher Tata McGraw Hill.
5. C: The Complete Reference, by Herbert Schildt, Publisher Tata McGraw
Hill.
6. Let us C, by Yashwant Kanitkar, Publisher BPB Publication
7. Schaum's Outline of Programming with C, By: Byron Gottfried, Publisher
Shaum Series.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

Chapter 1 Introduction to Programming: Algorithms and Flowcharts

A computer can neither think nor a make a judgment on its


own.
Program: A program is a set of logically related instructions
that is arranged in a sequence and guides the computer in
solving a problem.
Programming: The process of writing a program is called
programming.
Packaged Software: User can directly purchase readymade
existing program.
Customized Software: Developer prepare a new program from
scratch.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

1.1. Programs and Programming


Computer Software
System
Software

Computer
Software

Application
Software

System Software: It is a collection of programs that interfaces with the


hardware.
Categories of System Software are as follows:
1. Language Translator
2. Operating System
3. Utilities
4. Special Purpose Program
Language Translator: It is a system software that transforms a computer
program written by a user into a form that can be understood by the
machine.
Operating System: It is the master control system software which
manages the computers resources effectively, take care of scheduling
multiple jobs for execution, and manages the flow of data and instructions
between the input/output units and the main memory.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

1.1.1 System Software

Utilities: Utility programs are those that may be requested by


application programs many times during the execution phase.
Some examples are as follows:
1. SORT/MERGE for sorting large volumes of data and merging
them into a single sorted list.
2. Transfer programs for transforming data content from one
medium to another, e.g., disk to tape, tape to disk etc.
Special purpose software: Special programs are those that
extend the capability of operating systems to provide
specialized services to application programs. For e.g. loader,
linker, etc.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

1.1.2. Application Software

1.
2.
3.
4.
5.
6.

Application Software is written to enable the computer to solve a specific data


processing task.
There are two categories of application software : Pre-written software packages
and user application programs.
Characteristics of Application software:
Easy to learn and use compare to programming language
It performs many general and special functions.
In some of the application when it found inadequate then application programs
are written to meet the exact requirements.
A user application program may be written using one of these packages or a
programming language.
The most important categories of software packages available are:
Database management software
Spreadsheet software
Word processing, Desktop Publishing (DTP), and presentation software
Multimedia Software
Data Communication software
Statistical and operational research software
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

1.2. Programming Language

Programming Language: It is composed of a set of instructions


in a language understandable to the programmer and
recognizable by a computer.
It is classified into three categories:
1. High-level
2. Middle-level
3. Low-level
High-level languages such as BASIC, COBOL (COmmon Business
Oriented Language), FORTRAN (FROmula TRANlation) are used
to write application programs.
A middle-level language such as C is used for writing application
and system programs.
A low-level programming language such as the assembly
language is mostly used to write system programs.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

1.2.1. System Programming Languages


An example of system software is an operating system
consisting of many other programs that control i/o devices,
memory, processor, schedule the execution of multiple tasks,
etc.
To control the computers circuitry as well as manage the
resources of the computer.
Assembly language was used to write system programs.
But, today C is widely used to develop system software.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

10

1.2.2. Application Programming Languages


There are main two main categories of application programs:
Business Program and Scientific Application Program.
Application
programs are designed for specific computer
applications such as payroll processing and inventory control.
In application program, programmer does not need to control the
circuitry of computer but
Business applications are characterized by processing of large
inputs and high-volume data storage and retrieval but call for
simple calculations.
Scientific Application Program: Programming languages designed
for writing scientific programs contain very powerful instructions
for calculations but have poor instructions for input, output etc.
COBOL is more suitable for business applications whereas FORTRAN
is more suitable for scientific applications.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

11

1.2.3. Low-level language


A low-level computer programming language is closer to the native
language of the computer, which is 1s and 0s.
Machine Language:
Instructions are written in a sequence of 0s and 1s.
Machine language is considered as the first generation language
(1GL)
Advantage of Machine language:
The CPU directly understands machine instructions, hence no
translation is required.
It takes less execution time.
Disadvantages of Machine Language:
Difficult to use: It is difficult to understand and develop a program
using machine language.
Machine Dependent:
Error Prone: It is very difficult to remember the various combinations
of 1s and 0s.
Difficult to debug and modify:
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

12

Machine Language

Example 1:
Machine Code
0011
1100
0000
0111
0000
0110
0000
1010
1000
0000

10/11/2012

Comments
Load A register with value 7

Load B register with 10


A=A+B

Prepared By:Swaminarayan Priya, ISTAR

13

1.2.3. Low-level language


Assembly Language: In this language, various symbols such as letters, digits
or special characters are used to represent the operation, operand and
other parts of the instruction code.
This representations are known as mnemonic codes; they are used instead
of binary codes.
It is considered as a second generation language (2GL).
Each computer has its own assembly language that is dependent upon the
internal architecture of the processor.
An assembler is a translator which converts program from assembly
language to machine language.
An assembler is a translator which converts program from assembly
language to object code, which can then be executed by machine.
Note: The object code is the machine language code.

Mnemonics
LD A,7
LD B,10
ADD A,B
10/11/2012

Comments
Load register A with 7
Load register B with 10
A=A+B
Prepared By:Swaminarayan Priya, ISTAR

14

Assembly Language

Advantages of Assembly Language:


Easy to write and understand.
More readable.
Disadvantages of Assembly Language:
Machine dependent
Programming is difficult and time consuming.
The programmer should know all about the logical
structure of the computer.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

15

1.2.4. High-level languages


High-level languages such as COBOL, FORTRAN, BASIC etc. have
instructions that are similar to human languages.
It is also known as third-generation languages (3GL).
The time and cost of creating machine and assembly language programs
quite high.
Statement Number Program Statement
10
LET X = 7
20
LET Y = 10
30
LET SUM = X + Y
Advantages of high-level programming languages:
Readability: More readable than assembly and machine level language.
Portability:
Easy Debugging: Errors can be easily detected and removed.
Ease in the development of software.
Disadvantage of high-level language:
It takes more time for execution of program.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

16

1.3. Compiler, Interpreter, Loader and Linker


There are two kinds of translators exist: Compiler and Interpreter
Source Program in High Level Language Compiler Object Code in
Machine Level Language
Diagnostics: During the process of translation, the compiler reads the
source programs statement wise and checks for syntax errors. In case of any
error, the computer generates a printout of the same. This action is known
as diagnostics.
Compiler

Interpreter

Scans entire program before translating it


into machine code

Translates and executes the program line


by line

Converts entire program to machine code


and only when all the syntax errors are
removed does execution take place.

Each time the program is executed, every


line is checked for syntax error and then
converted to the equivalent machine
code.

Slow in debugging, i.e. removal of


mistakes from a program.

Good for fast debugging.

Execution time is less

Execution time is more.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

17

1.3.1 Compiling and Executing High-level Language Program


The compilation process consists of two steps:
1. The analysis of the source program
2. The synthesis of the object program in the machine language of
the specified machine.
The analysis phase uses the precise description of the source
programming language.
A source language is described using lexical rules, syntax rules and
semantic rules.
Lexical rules specify the valid syntactic elements or words of the
language.
Syntax rules specify the way in which valid syntactic elements are
combined to form the statements of the language.
Semantic rules assign meaning to valid statements of the language.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

18

The execution of a program written in high-level language


involves the following steps:
1. Translation of the program resulting in the object program.
2. Linking of the translated program with other object programs
needed for execution, thereby resulting in a binary program.
3. Relocation of the program to execute from the specific
memory area allocated to it.
4. Loading of the program in the memory for the purpose of
execution.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

19

Fourth Generation Languages (4GL)

It is non-procedural language that allows the user to specify what the output
should be without describing how data should be processed to produce the result.
It requires less instructions to accomplish a particular task than a third generation
language.
The programmer should be able to write a program faster in 4GL than 3GL.
The 3GL languages are procedural languages but 4GL languages are nonprocedural languages.
Major 4GLs are used to get information from files and databases.
DBMS Package

Some 4GLs are used to produce complex printed reports.


Eg. Of Report Generators are:

Jasper (For JAVA)


Crystal Report
Third Party Reports: Dundas S/ws (which produces reports, charts)
VB Report

Screen Painter
MS Publisher (Used for designing)
Dreamweaver
FrontPage

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

22

For e.g.
Step1: Get a record from the EMP file.
Step2: If this is the record for MANAS, display the address.
Step3: If this is not the record for MANAS, go to step 1, until end-of-file.

Advantages of 4GLs:
Programming productivity is increased. One line of a 4GL code is equivalent
to several lines of a 3GL code.
System development is faster.
Program maintenance is faster.
End users can often develop their own applications.
Programs developed in 4GLs are more portable than those developed in
other generation languages.
Documentation is of improved order because most 4GLs are selfdocumenting.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

23

Third Generation Languages

Fourth Generation Languages

Meant for use by professional


programmers.

May be used by non-professional


programmers as well as by professional
programmers.

Requires specifications of how to perform Requires specifications of what task to


a task.
perform.
System determines how to perform the
task.
All alternatives must be specified.

Default alternatives are built-in. User


need not specify these alternatives.

Requires large number of procedural


instructions.

Requires fewer instructions.

Code may be difficult to read, understand, Code is easy to understand and maintain.
and maintain by the user.
Difficult to debug.

Errors are easier to locate because of


shorter programs, more structured code
and use of defaults.

Typically, file oriented.

Typically, database oriented.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

24

Fifth Generation Languages(5GL)


Natural languages represent the next step in the
development of programming languages belonging to fifth
generation languages.
Natural language is similar to query language, but it
eliminates the need for the user or programmer to learn a
specific vocabulary, grammar or syntax.
The text of a natural-language is statement resembles human
speech closely.
It supports machine learning.
Natural languages already available for microcomputers
include CLOUT, Q & A and SAVY RETRIEVER (for use with
dbase) and HAL (Human Access Language) for use with
LOTUS.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

25

Classification of Programming Languages


1. Procedural Languages
2. Problem-oriented Languages
3. Non-procedural languages
Programming Language
High-level Language
Procedural

Non-procedural

1)Algorithmic
1) Functional
(COBOL, FORTRAN, C)
(LISP, ML)
2) Object-Oriented
2) Logic Based
(C++, JAVA, SMALLTALK) (PROLOG)
3) Scripting
(VB, PERL)

10/11/2012

Problem-oriented

Low-level Language
Machine

Assembly

1) Numeric
(MATLAB)
2) Symbolic
(MATHEMATICA)
3) Publishing
(LATEX)

Prepared By:Swaminarayan Priya, ISTAR

26

Structured Programming Concept

1.
2.

There is no standard definition of structured program.


Structured programming is
Better organization of programs.
It should be understandable, i.e. more easily modifiable and
suitable for documentation.
3. More economical to run.
4. More correct and therefore easy to debug.

1.
2.
3.

Structured Programming can be defined as a:


Top-down analysis for program solving.
Modularization for program structure and organization.
Structured code for individual modules.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

27

Top-Down Analysis
The basic steps to top-down analysis are as follows:

Step1: Determine the complete scope of the problem to determine the


basic requirement for its solution.
Step2: Based on the definition of the problem, divide the problem into
two or more separate parts.
Step3: Carefully define the scope of each of these separate tasks and
subdivide them further, if necessary, into two or more smaller tasks.
Step4: Repeat step 3 (Every step at the lowest level describes a simple
task, which cannot be broken further.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

28

Modular Programming
Modular programming is a program that is divided into logically
independent smaller sections, which can be written separately.
Characteristics of Modular programming are as follows:
A module consists of a series of program instructions.
A module is clearly terminated by some special marker. For eg. Return
statement in C language.
A module has a unique name.
A module has only one entry point and only one exit point from where the
control is returned to the calling module.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

29

Algorithms
Algorithm: It is an effective procedure for solving a problem in a finite
number of steps.

1.
2.
3.
4.
5.
6.

Eg. Of an algorithm: for making a pot of tea.


If the kettle dose not contain water, then fill the kettle.
Plug the kettle into the power point and switch it on.
If the teapot is not empty, then empty the teapot.
If the water in the kettle is not boiling, then go to step 5.
Switch off the kettle.
Pour water from the kettle into the teapot.

Key features of an Algorithm:


1. Sequence (also known as process)
2. Decision (also known as Selection)
3. Repetition (also known as iteration or looping)

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

30

Sequence: It means that each step or process in the algorithm is executed


in the specified order.
The decision constructs if..then, if..then..else..
The outcome of the decision is based on some condition.
For eg. If today is Friday then collect pay.
If proposition then process1 else process2.
The repetition constructs repeat and while
The repeat loop is used to iterate a process or sequence of processes until
some condition become true.
Repeat
Process 1
Process 2
While
.
.
Process N
Until proposition.

10/11/2012

While proposition
Begin
process1
process2
.
.
process N
end

Process1
Process2
.
.
Process N
If proposition
goto process1

Prepared By:Swaminarayan Priya, ISTAR

31

Rules for writing Algorithm


Each algorithm should have START and STOP statements.
To accept data from user, the INPUT or READ statements are to be
used.
To display any user message or the content in a variable, PRINT
statement will be used. The message will be enclosed within
quotes.
The arithmetic operators that will be used in the expressions are
Assignment =, Addition +, Subtraction , Multiplication *, Division /
In propositions, the commonly used relation operators will include,
>, <, >=, <=, =, !=
Note: a <- b is an assignment statement and a=b is a proposition for
checking the equality.
The most commonly used logical operators will be AND, OR, NOT

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

32

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

In an academic institute, grades have to be printed for students who appeared in the
final exam. The criteria for allocating the grades against the percentage of total marks
obtained are as follows.
Marks
Grade
Marks
Grade
91-100
O
61-70
B
81-90
E
51-60
C
71-80
A
<= 50
F
The percentage of total marks obtained by each student in the final exam is to be given
as input to get a printout of the grade the student is awarded.
START
PRINT ENTER THE OBTAINED PERCENTAGE MARKS
INPUT N
IF N > 0 AND N <= 50 THEN PRINT F
IF N > 50 AND N <= 60 THEN PRINT C
IF N > 60 AND N <= 70 THEN PRINT B
IF N > 70 AND N <= 80 THEN PRINT A
IF N > 80 AND N <= 90 THEN PRINT E
IF N > 90 AND N <= 100 THEN PRINT O
STOP

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

33

Construct an algorithm for incrementing the value of a


variable that starts with an initial value of 1 and stops when
the value becomes 5.
1.
START
2.
C=1
3.
WHILE C <= 5
4.
BEGIN
5.
PRINT C
6.
C=C+1
7.
END
8.
STOP

Write an algorithm for the addition of N given numbers.


1.
START
2.
PRINT HOW MANY NUMBERS?
3.
INPUT N
4.
S=0
5.
C=1
6.
PRINT ENTER NUMBER
7.
INPUT A
8.
S=S+A
9.
C=C+1
10. IF C <= N THEN GOTO 6
11. PRINT S
12. STOP
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

Develop an algorithm for


finding the sum of the series
1+2+3+4+.. up to N terms.
1. START
2. PRINT HOW MANY
TERMS?
3. INPUT N
4. S = 0
5. C = 1
6. S = S + C
7. C = C + 1
8. IF C <= N THEN GOTO 6
9. PRINT S
10. STOP

34

Write an algorithm for


Write an algorithm for
determining the sum of the
calculating the factorial of a
series 2 + 4 + 8 + -- up to N.
given number N.
1. START
2. PRINT ENTER THE VALUE
OF N
3. INPUT N
4. S = 0
5. C = 2
6. S = S + C
7. C = C * 2
8. IF C <= N THEN GOTO STEP 6
9. PRINT S
10. STOP

10/11/2012

1. START
2. PRINT ENTER THE NUMBER
3. INPUT N
4. F = 1
5. C = 1
6. While C <= N
7. BEGIN
8. F = F * C
9. C = C + 1
10. END
11. PRINT F
12. STOP

Prepared By:Swaminarayan Priya, ISTAR

35

Write an algorithm for


computing the sum of the
series 1+x+x2/2!+x3/3!+-- up
to N terms.
1. START
2. PRINT ENTER NUMBER OF
TERMS
3. INPUT N
4. PRINT ENTER A NUMBER
5. INPUT X
6. T = 1
7. S = 0
8. C = 1
9. S = S + T
10. T = T + X / C
11. C = C + 1
12. IF C <= N THEN GOTO STEP 9
13. PRINT S
14. STOP
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

36

Flowchart
It is a pictorial representation of the sequence of operations in a
computer program.
Standards for flowchart:
Flowcharts must be drawn on white, unlined paper, on one side
only.
Flowcharts start on the top of the page and the flow down and to
the right.
Only standard flowcharting symbols should be used.
English should be used in flowcharts, not programming language.
The flowchart for each subroutine, if any, must appear on a
separate page. Each subroutine begins with a terminal symbol with
the subroutine name and a terminal symbol labeled return at the
end.
Draw arrows between symbols with a straight edge and use
arrowheads to indicate the direction of the logic flow.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

37

Flowchart Symbols

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

38

Guidelines for flowcharts


There should be a logical start and stop to the flowchart.
The flowchart should be clear, neat and easy to follow. There
should be no ambiguity in understanding the flowchart.
The usual direction of the flow of a procedure or system is
from left to right or top to bottom.
Only one flow line should enter a decision symbol, but two or
three flow lines, one for each possible answer, can leave the
decision symbol.
False

Only one flow line is used in


Trueconjunction with a terminal
symbol.
START

STOP
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

39

A sequence of steps or processes


that are executed in a particular
order is shown using process symbols
connected with flow lines.

Selection of a process or step is


depicted by the decision making and
process symbols.

Iteration or looping is depicted by a


combination of process and decision
symbol.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

40

Draw a flowchart to find


the sum of the first 50
natural numbers.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

41

Draw a flowchart to find the largest of three numbers A,B, and C.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

42

Draw a flowchart for


computing N!.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

43

Draw a flowchart for calculating the simple interest using the formula SI = (P * R
* N)/100, where P denotes the principal, T time and R rate of interest. Also
write an algorithm for the same.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

44

The XYZ construction company plans to give a 5% year-end bonus to each of its
employees earning Rs. 5,000 or more per year, and a fixed bonus of Rs. 250 to all
other employees. Draw a flowchart and write the step-form algorithm for printing
the bonus of any employee.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

45

Prepare a flowchart to read the marks of a student and classify them into different grades. If the
marks secured are greater than or equal to 90, the student is awarded Grade A; if they are
greater than or equal to 80, but less than 90, Grade B is awarded; if they are greater than or
equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is awarded.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

46

Draw a flowchart to find the roots of a quadratic equation.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

47

Draw a flowchart for printing the sum of even terms contained within
the numbers 0 to 20.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

48

Advantages of using flowcharts


Communication: Flowcharts are a better way of communicating the
logic of a system to all concerned.
Effective Analysis: With the help of flowcharts, problems can be
analyzed more effectively.
Proper Documentation: Program flowchart serves as a good program
documentation needed for various purposes.
Efficient coding: Flowchart act as a guide during the system analysis and
program development phase.
Proper Debugging: Flowcharts help in the process of debugging.
Efficient program maintenance: The maintenance of an operating
program becomes easy with the help of a flowchart.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

49

Limitations of using flowcharts


Complex logic: Sometimes, the program logic is quite
complicated. In such a case, a flowchart becomes complex
and clumsy.
Alterations and modifications: If alterations are required, the
flowchart may need to be redrawn completely.

Reproduction: Since the flowchart symbols cannot be typed


in, the reproduction of a flowchart become a problem.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

50

Chapter 2 : Basics of C

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

51

History of C Language
C is a structured, high-level, machine independent language.
The root of all modern languages is ALGOL, introduced in the
early 1960s.
ALGOL was the first computer language to use a block
structure.
In 1967, Martin Richards developed a language called BCPL
(Basic Combined Programming Language).
In 1970, Ken Thompson created a language using many
features of BCPL and called it B language.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

53

B was used to create early versions of UNIX operating system at


Bell Laboratories.
C was evolved from ALGOL, BCPL, and B by Dennis Ritchie at the
Bell Laboratories in 1972.
C uses many concepts from these languages and added the
concepts of data types and other powerful features.
C is strongly associated with UNIX operating system. UNIX is the
one of the most popular network OS and the heart of the
Internet data superhighway.
In 1983, American National Standards Institute (ANSI)
appointed a technical committee to define a standard for C.
The committee approved a version of C in December 1989
which is known as ANSI C.
It was approved by the ISO (International Standards
Organization) in 1990, this version is referred as C89.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

54

During 1990s, C++, a language entirely based on C.


C++ added several new features to C to make it not only a true
object-oriented language but also a more versatile language.
During the same period, Sun Microsystems of USA created a
new language JAVA modeled on C And C++.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

55

Basic Structure of C Program

Documentation Section
Preprocessor Directive Block
Definition Section
Global Declaration Section
main() Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function 1
Function 2
.
.
Function n

10/11/2012

(User-defined Functions)

Prepared By:Swaminarayan Priya, ISTAR

56

Escape Sequence: It is used in printf statement to format the output.

10/11/2012

Code

Meaning

\a

Ring terminal bell (i.e. a for alert)

\?

Question Mark

\b

Backspace

\r

Carriage return

\f

Form feed

\t

Horizontal tab

\v

Vertical tab

\0

ACSII Null character

\\

Backslash

Double quote

Single quote

\n

New line

\o

Octal

\x

Hexadecimal constant
Prepared By:Swaminarayan Priya, ISTAR

59

Character Set
The characters that can be used to form words, numbers and
expressions depend upon the computer on which the program is
run.
The characters in C are grouped into the following categories:
Letters
Digits
Special Characters
White space
Note: The compiler ignores white spaces unless they are a part of a
string constant.
White spaces may be used to separate words, but are prohibited
between the characters of keywords and identifiers.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

60

C Token
In a passage of text, individuals words and punctuation marks are called
tokens.
Identifiers:
An identifier is a sequence of characters invented by the programmer to
identify a specific object.
Rules for writing an identifier:
It is case sensitive. Ie NUMBER, Number and number are different
identifiers.
The underscore should not be used as the first character of a variable
name.
A numeric digit should not be used as the first character of identifier.
Identifier name should not be a keywords of C.
Identifiers may be of any reasonable length; generally 8 to 10 characters
should be suffice.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

61

Keywords

10/11/2012

auto

double

int

struct

break

else

long

switch

case

enum

char

Register

union

return

extern

Typedef

const

float

short

Unsigned

continue

for

signed

void

default

goto

sizeof

Volatile

do

if

static

while

Prepared By:Swaminarayan Priya, ISTAR

62

Data Types of C
Data Type

Primitive/Ba
sic Data Type
1. Character
2. Int
3. Float
4. double

10/11/2012

Derives Data
Type
1. Array
2. Function
3. pointer

User-defined
Data Type
1. Structure
2. Union
3. enumerated

Valueless
Data Type
1. void

Data type

Size (bits)

Range

Char

8 (1 B)

-128 to 127

Int

16 (2 Bytes)

-32768 to 32767

Float

32 ( 4 Bs)

3.4E-38 to 3.4E+38

Double

64 (8 Bs)

1.7E-308 to 1.7E+308

valueless

Void

Prepared By:Swaminarayan Priya, ISTAR

63

Data type

Format
Specifier

Size (bits)

Range

Char

%c

8 (1 B)

-128 to 127

unsigned char

%c

8 (1 B)

0 to 255

signed char

%c

8 (1 B)

-128 to 127

int

%d

16 (2 Bytes)

-32768 to 32767

Unsigned int

%u

16 (2 Bytes)

0 to 65535

Signed int

%d

16 (2 Bytes)

-32768 to 32767

Short int

%hd or %hi

16 (2 Bytes)

-32768 to 32767

Unsigned short int

%u

16 (2 Bytes)

0 to 65535

Signed short int

%hd

16 (2 Bytes)

-32768 to 32767

long int

%ld

32 (4 Bytes)

-2147483648 to 2147483647

Unsigned long int

%lu

32 (4 Bytes)

0 to 4294967295

Signed long int

%ld

32 (4 Bytes)

-2147483648 to 2147483647

Float

%f

32 ( 4 Bs)

3.4E-38 to 3.4E+38

Double

%lf

64 (8 Bs)

1.7E-308 to 1.7E+308

Long double

%Lf

80 (10 Bs)

3.4E-4932 to 1.1E+4932

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

64

Constant
It is a memory location whose value does not change during
the program execution.
EX:- PI=3.14
Constants are defined inside the program by the programmer
whereas the value of variable is read at the execution time
and give by the user.
How to declare constant?
#define PI 3.14
Or
const float PI = 3.14;

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

65

Operator
Arithmetic

Assignment

Equality

Relational

Logical

Bitwise

Unary Binary Ternary

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

66

Assignment Operator
In C, the assignment operator is the equal sign =
and is used to give a variable the value of an
expression.
For example:
i=0;
x=34.8;
sum=a+b;
slope=tan(rise/run);
midinit='J';
j=j+3;
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

67

Sizeof() operator

sizeof can be applied to types and objects; when used with an object, brackets are not
needed.
sizeof(char) is always 1.
Syntax is:
int i;
i = sizeof(int);
i will be set to 2, assuming a 16 bit system.
The result of sizeof is the amount of data used for an object in multiples of char.
void main()
{
printf(char size = %d bytes\n,sizeof(char));
printf(short size = %d bytes\n,sizeof(short));
Char size = 1 bytes
printf(int size = %d bytes\n,sizeof(int));
Short size = 2 bytes
printf(long size = %d bytes\n,sizeof(long));
Int size = 2 bytes
printf(float size = %d bytes\n,sizeof(float));
Long size = 4 bytes
printf(double size = %d bytes\n,sizeof(double));
Float size = 4 bytes
printf(1.55 size = %d bytes\n,sizeof(1.55));
printf(1.55L size = %d bytes\n,sizeof(1.55L));
Double size = 8 bytes
printf(Hello size = %d bytes\n,sizeof(Hello));
1.55 size = 8 bytes
}
1.55L size = 10 bytes

Hello size = 6 bytes

Note: In string, sizeof counts Null character also)


1.55 is float number but internally TC converts this float number into double, and double needs 8 bytes
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

68

Arithmetic Operators

*
/
%
+
-

multiplication
division
remainder after division (modulo arithmetic)
addition
subtraction and unary

int main()
{
float a;
a = 1 / 3;
printf("%f\n", a);
return 0;
}

0.3333333

would print 0.000000 as integer division was performed even though a is of type
float.
The / operator is used for two different operations: integer and floating point
division.
If both operands of the divide operator are of integral (char, int and its derivatives)
type then integer division is performed.
If either operand is float ,double or long double then real division is undertaken.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

69

Arithmetic operator :
+,-,*,/,%(modules)
% (Modules) operator is used to find the reminder after division.
EX : 20%8 will generate result 4(reminder).
The sign of result will be the same as sign of first operand (data).
Only integer values can be given with % operator, float and double type
data can not be supported.

Operator

Name

Example

Addition

12 + 4.9 = 16.9

Subtraction

3.98 4 = -0.02

Multiplication

2 * 3.4 = 6.8

Division

9 / 2.0 = 4.5

Remainder

13 % 3 = 1

9/2=4
-9/2 = -4
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

printf((%d\n,-5%-2);
printf((%d\n,-5%2);
printf((%d\n,5%-2);
printf((%d\n,5%2);

-1
-1
1
1
70

Increment and Decrement Operators


Increment and decrement operators give a shorthand method of
adding/subtracting 1 from an object.
++ increment
-- decrement
These operators can be prefix or postfix. An example of the different
behavior of the prefix and postfix forms is given below, but essentially with
the prefix form the variable is changed before the value of the expression
in which it appears is evaluated, and with the postfix form the variable is
modified afterwards.
b = 3;
a = b++ + 6; /* a = 9, b = 4 */
b = 3;
a = ++b + 6; /* a = 10, b = 4 */

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

71

Comma Operator

Syntax:
expressionM = (expression1, exp2, .. , exp n);
The comma operator can be used to link the related expressions together.
A comma-linked list of expressions are evaluated left to right and value of
the right-most expression is the value of the combined expression.
For e.g.
value = ( x = 10, y = 5, x+y);
for ( n = 1, m = 10, n <= m, n++, m++)
int i = 0;
int j;
J = (i += 1, i +=2; i +3);
Answer: j = 6

10/11/2012

int m = 1;
int n;
n = (m = m + 3, m%3);
Answer: N = 1

Prepared By:Swaminarayan Priya, ISTAR

int a = 2, b = 3, c;
c = a, a=b, b = c;
printf(a=%d b =%d,a,b);
Answer: a = 3 b = 2

72

Relational Operator

10/11/2012

Operator

Action

Example

==

Equal

5 == 5 ( result
1)

!=

Not equal

5 != 5 ( result 0)

<

Less than

5 < 5.5 ( result


1)

<=

Less than equal

5 <= 5 ( result
1)

>

Greater than

5 > 5.5 ( result


0)

>=

Greater than
equal

6.3 >= 5 ( result


1)

Prepared By:Swaminarayan Priya, ISTAR

73

Logical Operator
Operator

Action

Example

Result

Logical Negation

! ( 5 == 5)

&&

Logical AND

5 < 6 && 6 < 6

||

Logical OR

5 < 6 || 6 <5

C doesn't have a built-in Boolean type. It is compulsory to use the type int for this
purpose.
For eg.
int sorted = 0; // false
Int balanced = 1; // true

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

74

Conditional Operator

It is ternary operator.
It has the general form:
Expression1 ? Expression2 : expression3
First expression1 is evaluated; if the result is non-zero, then expression2 is
evaluated and its value is the final result. Otherwise, expression3 is
evaluated and its value is the final result.
For example,
If ( m < n) min=m; else min = n;
Min = (m <n ? m, n);
Write a program to find minimum number among three numbers using
conditional operator.
Int m=1, n=2, p = 3, min;
min = ( m<n ? (m<p?m:p) : (n<p?n:p));
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

75

void main()
{
int a=5,b=3;
printf(%d, ++(a*b+2));
}
Compiler error Lvalue required

10/11/2012

void main()
{
printf(%d, ++2);
}

Compiler error Lvalue required

Prepared By:Swaminarayan Priya, ISTAR

76

Bitwise Operator
Generally character, integer, float etc operate with a byte. But if we want to interact
directly with the computer hardware then we must have to work at bit level. This is
possible only through Bitwise Operators.
One of the powerful feature is a set of bit manipulation operators. Those permit user to
access and manipulate individual bits within a piece of data.
Operator

Action

Bitwise Negation

&

Bitwise AND

Bitwise OR

Bitwise Exclusive OR

<<

Bitwise Left Shift

>>

Bitwise Right Shift

These operators can operate upon int or char but not on float and double.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

77

1s Complement Operator:
Here all 1s present in the number are changed to 0s and all 0s are
changed to 1s.
Eg. A = 1010 then ~A = 0101
This operator is effectively useful in development of encryption facility.
Right Shift Operator:
Here >> operator shifts each bit in the operand to the right. The number
of places the bits are shifted depends on the number following the
operand.
E.g. 1101 0111 >> 3
0 110 1011 - 1 time
00 11 0101 - 2 time
000 1 1010 - 3 time

Note: Result of right shift operator is same as operand1 / 2.


64 >> 2 = 64/2 = 32 >> 2 = 32/2 = 16 >> 2 = 16/2 = 8
27 >> 1 i.e. 27 / 2 = 13
49 >> 1 i.e. 49/2 = 24

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

78

Lift Shift Operator <<


It is same is right shift operator but here bits are shifted to the left and on
right end side 0 is added.
5225 << 3
0001 0100 0110 1001
0000 1010 0011 0100 - 1st time
0000 0101 0001 1010 - 2nd time
0000 0010 1000 1101 - 3rd time
Note: Left shift operator is same as multiple of 2.
6 << 1 i.e. 6 * 2 = 12
6 << 2 i.e. 6* 2 = 12 * 2 = 24

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

79

Bit wise AND operator : &


It operates on two operands.
While operating upon these two operands they are compared on a bit by bit basis.
Here both the operands must be of the same type (either char and int)
E.g. 2 & 3
0000 0010 2
0000 0011 3
---------------0000 0010 2
Bit wise OR operator : |
E.g. 2 | 3
0000 0010 2
0000 0011 3
---------------0000 0011 3

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

80

Bit wise XOR operator : ^


The XOR returns 1, when any one of the two bits
or both the bits are 0. But XOR returns 1 only if
one of the two bit is 1.
E.g. 2 | 3
0000 0010 2
0000 0011 3
--------------- 0000 0011 3
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

81

Expressions and Statements


An expression in C is some combination of constants,
variables, operators and function calls.
Sample expressions are:
a+b
3.0*x - 9.66553
tan(angle)
Most expressions have a value based on their contents.
A statement in C is just an expression terminated with a
semicolon.
For example:
sum = x + y + z;
printf("Go Buckeyes!");
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

82

Operator Precedence Chart


Operator Type

Operator

Associativity

Primary Expression
Operators

() [] . -> expr++ expr--

left-to-right

Unary Operators

* & + - ! ~ ++expr --expr


(typecast) sizeof

right-to-left

Binary Operators

Ternary Operator
Assignment Operators
Comma

10/11/2012

*/%
+>> <<
< > <= >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= >>= <<=
&= ^= |=
,

Prepared By:Swaminarayan Priya, ISTAR

left-to-right

right-to-left
right-to-left
left-to-right

83

X = 7 * 6 % (15 / 9);

X = 2 * 3 + 4 * 5;

Answer : X = 26
X = 2 * ( 3 + 4 ) * 5;
Answer: X = 70
X = 7*6 % 15/9;
Answer: X = 1
X = 7 * ( 6 % 15) / 9;
Answer: X = 4
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

84

Automatic Type Conversion with


Assignment Operator
Automatic conversion even takes place if the
operator is the assignment operator. This creates a
method of type conversion.
For example, if x is double and i an integer, then
x=i;
i is promoted to a double and resulting value given
to x

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

85

Type Conversion in C
When a C expression is evaluated, the resulting value has a particular data
type. If all the variables in the expression are of the same type, the
resulting type is of the same type as well.
For eg.,if x and y are both of int type, the expression x + y is of int type as
well.
The smallest to the largest data types with respect to size are given as
follows:
Char -> int -> long -> float -> double
1 byte -> 2 B -> 4 B -> 4 B -> 8 B
Thus, an expression containing an int and a char evaluates to type int.
An expression containing a float and a long evaluates to type float.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

86

Note: within expressions, individual operands are promoted as necessary


to match the associated operands in the expression.
If both operands are of the same type, promotion is not needed. If they
are not, promotion follows these rules:
Float operands are converted to double.
Char or short (signed or unsigned) are converted to int (signed or
unsigned).
Long double
double
float
Unsigned long int
Long int

Unsigned int
int
short
Char

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

87

Conversion by Assignment
Promotion also occur with the assignment operator. The expression on the
right side of an assignment statement is always promoted to the type of
the data object on the left side of the assignment operator.
For eg.
Char c;
Int j;
Float f;
Double d, r;
R = (c * j) + (f / j) ( f + d);
R = ( char * int ) + ( float / int ) ( float + double)
R = double

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

88

Type Casting
The opposite of promotion, truncation moves a value from a
particular type to a smaller type.
In this case, the compiler just drops the extra bits. It may or may
not generate a compile time warning for the loss of the
information.
For example,
(double) I
will force i to be of type double.
The general syntax is
(type) expression
Some examples,
x = (float) 77;
(double) k * 57

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

89

Char ch;
Int I;
I = 321;
Ch = I; /* truncation of an int value to fit in a char */

Content of i

0000 0001

Content of ch after ch = I
statement is executed
Double pi;
Int I ;
Pi = 3.14159;
I = pi;
printf(d,i);
10/11/2012

0100 0001

Binary equivalent of 321

0100 0001

Prepared By:Swaminarayan Priya, ISTAR

Binary equivalent of 65

90

1: Which of the following is an incorrect


assignment statement.
a) N = m = 0
b) mySize = x < y ? 9 : 11
c) Value += 10
d) testVal = ( x> 5 || x < 0)
e) None of the above

Answer: 65

E- None of the above

1: What will be the output:


a) Int main()
{
float c = 3.14;
printf(%f,c%2);
return(0);
}

3 What will be the output:


a) Int main()
{
double d = 1/2.0 1/2
printf(%f, d);
return(0);
}

Floating point cannot be used with % operator


10/11/2012

2: What will be the output:


a) Int main()
{
printf(%d,A);
return(0);
}

0.500000

Prepared By:Swaminarayan Priya, ISTAR

91

4 What will be the output:


a) Int main()
{
char c = A;
printf(%c, c + 10);
return(0);
}
Answer: K

5 What will be the output:


a) Int main()
{
printf(Work Hard);
return(0);
}
Answer: WorkHard
10/11/2012

5 What will be the output:


a) Int main()
{
int c = --2;
printf(c = %d,c);
return(0);
}
Answer: Lvalue required.

5 What will be the output:


a) Int main()
{
int c = - -2;
printf(c = %d,c);
return(0);
}
Answer: c = 2
Prepared By:Swaminarayan Priya, ISTAR

92

8 What will be the output: 8 What will be the output:


10 What will be the output:
a) Int main()
a) Int main()
a) Int main()
{
{
{
int a = 5,i;
int a = 5,i;
int i = 5;
i = !a > 10;
i = !(a > 10);
printf(I =` %d, i);
printf(I =` %d, i);
printf(%d%d%d, i++,I,++i);
return(0);
return(0);
return(0);
}
}

Answer: 0
9 What will be the output:
a) Int main()
{
printf(\nab);
printf(\bsi);
printf(\rha);
return(0);
}
\n newline
\b backspace
\r - linefeed
10/11/2012

Answer = 1

Answer: 6 6 6
10 What will be the output:
a) Int main()
{
int i = 5;
printf(%d%d%d, i++,i,i++);
return(0);
}
6 6 5

Prepared By:Swaminarayan Priya, ISTAR

93

12 What will be the output:


a) Int main()
{
int a = 5;
printf(%d%d%d, ++i,++i,++i);
return(0);
}
8 7 6

13 What will be the output:


a) Int main()
{
int a = 5;
a = printf(Good) + printf(Bye);
printf(a = %d,a);
return(0);
}

14 What will be the output:


a) Int main()
{
int a = 5;
printf(%d,scnaf(%d,&i));
return(0);
}
2 Note: scanf returns total no of variables
read by that statement.
15 What will be the output:
a) Int main()
{
char n;
n = !2;
printf(%dn);
return(0);
}

7
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

94

16 What will be the output:


a) Int main()
{
char n;
n = !0;
printf(%d,n);
return(0);
}

18 What will be the output:


a) Int main()
{
int x = 10,y=15,a,b;
a = x++;
b = ++y;
printf(%d%d \n,a,b);
return(0);
}

17 What will be the output:


a) Int main()
{
int I = -2
printf(-I = %d \n,-i);
return(0);
}

19 What will be the output:


a) Int main()
{
int x = 10,y=15,a,b;
x = x++;
y = ++y;
printf(%d%d \n,x,y);
return(0);
}

2
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

95

20 What will be the output:


a) Int main()
{
int x = 10,y=15;
printf(%d,++(x+y));
return(0);
}
Lvalue Required

21 What will be the output:


a) Int main()
{
int x = 1,y=5;
printf(%d,++x+y);
return(0);
}
26

10/11/2012

22 What will be the output:


int a =8, b = 3, x1,x2,x3,x4;
X1 = a*b
x2 = a/b
X3 = a%b
x4 = a && b
printf(%d,x1);
printf(%d,x2);
printf(%d,x3);
printf(%d,x4);
X1 = 24 x2 = 2 x3 = 2 x4 = 1

23 What will be the output:


a) Int main()
{
int a = 7, b = 2;
float c;
c = a/b;
printf(%f,c);
3.000000
return(0);
}
Prepared By:Swaminarayan Priya, ISTAR

96

Chapter 3
Input and Output

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

97

Basic Screen & Keyboard I/O in C


Following are standard files or streams:
1. stdin: connected to the keyboard.
2. stdout: connected to the screen
3. stderr: connected to the screen
Following are two data streams available on MS-DOS based
computers, but not on UNIX or other multi-user based operating
system:
1. stdaux: connected to the first serial communications port
2. stdprn: connected to the first parallel printer port

The <stdio.h> header file contains the various declarations


necessary for the functions.
The input/output functions fall into two categories: nonformatted read (input) and display (output) functions and
formatted input/output functions.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

98

Non-formatted Input and Output


It can handle one character at a time.
For the input functions it doesnt require <Enter> key to be pressed
after the entry of the character.
For the output functions, it prints the single character on the
console.
Single character Input:
The getchar() input function reads an unsigned char from the input
stream stdin. And convert it into int, which is the return value.
Syntax:
char_variable = getchar();
For e.g.
int ch;
ch = getchar();

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

99

Single Character Output:


The putchar() function writes a character to the stdout data stream. It returns
the character, On error, putchar() returns EOF.
Syntax:
putchar(char_variable);
Where char_variable is the name of the variable that is of type char.
For e.g.
int ch;
ch = getchar();
putchar();
Additional Single Character Input and Output Functions:
getch() This input function reads, without echoing on the screen, a single
character from the keyboard and immediately returns that character to the
program.
ch = getch(); // ch is a character variable.
getche() This input function reads, with echo on the screen, a single
character from the keyboard and immediately returns that character to the
program.
ch = getche(); // ch is a character variable.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

100

Void main()
{
char ch;
ch = getch();
putch(ch);
}
Output: a
10/11/2012

Void main()
{
char ch;
ch = getche();
putch(ch);
}
Output: aa
Prepared By:Swaminarayan Priya, ISTAR

101

Input and Output


putch() This output function writes the character directly to the
screen.
On the success, putch() returns the character printed, on error, it
returns EOF.
putch(ch); // ch is a character variable.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

102

Example -1 : Display a given character


void main()
{
int ch;
ch = 'A';
putchar(ch);
}
// Output: A
Example 2: Display a keyedin character.
void main()
{
int ch;
clrscr();
ch = getchar();
putchar(ch);
}
Input: Z
Output: Z
10/11/2012

Example 3: Accept a character and display the


next character from the ASCII table
Input: A
Output: B
void main()
{
int ch;
ch = getchar();
ch++;
putchar(ch);
}
Example 4: Double output of next two
characters from the ASCII table.
Input: a
Output: bbcc

void main()
{
int ch;
ch = getchar();
ch++;
putchar(ch);
ch++;
putchar(ch);
}
Prepared By:Swaminarayan Priya, ISTAR

putchar(ch);
putchar(ch);
103

Read small letter and convert it into upper


letter.
Input: a
Output: A
Compare two numbers:

void main()
{
char ch;
ch = getchar();
ch = ch - 32;
putchar(ch);
}

10/11/2012

void main()
{
char ch1, ch2;
clrscr();
ch1 = getchar();
ch2 = getchar();
ch1 == ch2 ? printf("Equal") : printf("Not Equal");
}

Prepared By:Swaminarayan Priya, ISTAR

104

Convert Upper letter to lower cases


void main()
{
int ch,ch1;
ch = getchar();
if (ch >= A' && ch <= Z')
ch1 = ch + 32;
else
ch1 = ch;
putchar(ch1);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

105

gets() it is used to read string from keyboard.


puts() it is used to print string on the monitor.

Note: All above functions require the header file <conio.h> to be


included.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

106

Specifier Type
%c character
%d decimal integer
%o octal integer (leading 0)
%x hexadecimal integer (leading 0x)
%u unsigned decimal integer
%ld long int
%f
floating point
%lf double or long double
%e exponential floating point
%s character string
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

108

Formatting the output in printf()


We can control how many columns will be used to output the contents
of a particular variable by specifying the field width.
The desired field width is inserted in the format specifier after the %
and before the letter code indicating the data type.
% Flag Min.Width

Precision

size

ConversionCode

Here, % sign and conversion code are required but the other modifiers
such as width and precision are optional.
The width modifier specifies the total no. of characters used to display the
value.
The precision indicates the no. of characters used after the decimal
points. But it is used only with the floats and strings.
When it is used with float, the precision indicates how many digits should
be printed after the decimal point.
If the precision is not specified, the default value of 6 is assumed.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

109

1 0
printf(number=%3d\n,10);
printf(number=%2d\n,10); 1 0
printf(number=%1d\n,10); 110 0
5 . 4 3
printf(number=%7.2f\n,5.4321);
. 4 4
printf(number=%.2f\n,5.4391); 55.44
printf(number=%.9f\n,5.4321);5 . 4 3 2 1 0 0 0 0
printf(number=%f\n,5.4321); 5 . 4 3 2 1 0 0

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

110

Flag

Meaning

Left justify the display

Display positive or negative sing of value

Space

Display space if there is no sign

Pad with leading zero

Use alternate form of specifier

printf(number=%06.1f\n,5.5);

printf(number=%-+6.1f\n,5.5);

printf(%-6.3f\n,17.23478);

Note: Default justification for string and number is


right but if - flag is used then it will be left justified.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

111

Void main()
{
h e
printf(%s,hello);
printf(%3s,hello); h e
printf(%10s,hello);
printf(%-10s,hello); H E
printf(%10.3s,hello);
}

10/11/2012

o
H E L

Prepared By:Swaminarayan Priya, ISTAR

H E L

112

Flag with
format
specifier

Action

%#0

Adds a leading 0 to the octal number printed

%#x or X Adds a leading Ox or OX to the hex number printed


%#f or e

Ensures that the decimal point is printed

%#g or G

Display trailing zeros in g or G type conversion and ensures


decimal point is printed in floating-point number, even though it is
Void main() a whole number.
{

int x = 20;
printf(Octal value of %d = %o,x,x);
printf(Hexa value of %d = %x,x,x);

o/p: Octal value of 20 = 24


o/p: Hexa value of 20 = 14

printf(Octal value of %d = %#o,x,x);


printf(Hexa value of %d = %#x,x,x);

o/p: Octal value of 20 = 024


o/p: Hexa value of 20 = 0X14

}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

113

float f=12;
printf(%f,f);
printf(%#f,f);
printf(%e,f);
printf(%g,f);
printf(%#g,f);
f = 122
F = 1223
F = 12345
F = 123456
F = 1234567
10/11/2012

o/p: 12.000000
o/p: 12.000000
o/p: 1.200000e+01
o/p: 12
o/p: 12.0000

printf(%#g,f);
printf(%#g,f);
printf(%#g,f);
printf(%#g,f);
printf(%#g,f);

o/p: 122.000
o/p: 1223.00
o/p: 12345.0
o/p: 123456.
o/p: 1.23457e+06

Prepared By:Swaminarayan Priya, ISTAR

114

void main()
{
float p = 3.123456,q=1.12,r=123;
clrscr();
printf("%f
%f
%f",p,q,r);
printf("\n%g
%g
%g",p,q,r);
printf("\n%#g
%#g
%#g",p,q,r);
}

Output:
3.123456
3.12346
3.12346

1.120000
1.12
1.12000

123.000000
123
123.000

If #g is used then it will display number within 7 positions.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

115

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

116

Control Code

Action

\b

Backspace

\f

Form feed

\n

New line

\r

Line feed

\t

Horizontal tab

Single quote

\0

null

Sample output:
printf(Hello world)
Int i1=2,i2=3; printf(sum is %d,i1+i2);
printf(%3d\n%3d\n%3d\n,5,25,125);

PI = 3.1415926535 Printf(%4.2f,pi);

o/p: Hello world


o/p: sum is 5
o/p:
5
25
125
o/p: 3.14

Char color*10+ = red;


printf(Color is %s,color);
printf(Color is %10s,color);
printf(Color is %-10s,color);

o/p: Color is red


o/p: Color is
red
o/p: Color is red

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

117

Input function scanf()


The scanf() function works in much the same way as the printf().
General form of scanf() statement is,
scanf(control_string,var1_address, var2_address,);
Where the control string is also known as format string is a list of
format specifiers indicating the format and type of data to be read
from the standard input device.
There must be the same no of format specifiers and addresses as
there are input fields.
scanf(%d%d%d%c,&a,&b,&c,&x);
Assume that the user wants a,b,c and x to be 1,2,3 and z. The user
would have to type 1 2 3z
If, instead, the user types 1 2 3 z then the value of x will be a space.

If the user wants to be able to enter the line this way, the scanf ()
needs to be coded as follows:
10/11/2012
scanf(%d%d%d %c,&a,&b,&c,&x);
Prepared By:Swaminarayan Priya, ISTAR

118

Note: Using spaces between integer field specifications is optional.


For eg., while reading integers x,y and z
scanf(%d%d%d,&a,&b,&c);
Is equivalent to
scanf(%d %d %d,&a,&b,&c);
If a width modifier is used, it specifies the maximum no. of
characters to be read.
Then scanf() will read either as many characters as specified by the
width modifier or until it sees white space.
void main()
{
int no;
scanf(%2d,&no);
printf(%d,no);
no++;
printf(%d,no);

if input is 12345
output is only 12
13
output is 13

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

119

Void main()
{
int a,b,c;
int num;
num = scanf(%d%d%d,&a,&b,&c);
printf(I have read %d values \n,num);
}
Suppose Input = 10 20 30
Then O/p = I have read 3 values.
If Input = 10 20 hello
Then O/p = I have read 2 values.
If Input = hello 10 20 30
Then O/p = I have read 0 values.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

120

void main()
{
int x;
scanf(You typed %d\n,x);
}

Note: In scanf() statement, the format string


should never end with a new line character.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

121

Print formatted number.


/123/
/123_-_-_-_/
/-_-_-_-123/
void main()
{
printf(%d,123);
printf(%-10d,123);
printf(%10d,123);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

122

Print formatted floating-point number


/1234.560000/
/1.234560e+03/
/1235/
/1234.6/
/1234.560_-/
/_-1234.560/
/_1.235e+03/
Void main()
{
printf(%f\n,1234.56);
printf(%e\n,1234.56);
printf(%4.f\n,1234.56);
printf(%6.1f\n,1234.56);
printf(%-10.3f\n,1234.56);
printf(%10.3e\n,1234.56);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

123

#define test Outstanding Program!


Void main()
{
printf(/%2s/\n,test);
printf(/%22s/\n,test);
printf(/%22.5s/\n,test);
printf(/%-22.5s/\n,test);

}
/Outstanding Program!/
/ Outstanding Program!/
/
Outst/
/Outs
/

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

124

Chapter: 4
Control Statements
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

126

Control Statement
Statement: A statement is a syntactic construction that performs an action
when a program is executed.
Statement blocks: In C, any sequence of statements can be grouped
together to function as a syntactically equivalent single statement by
enclosing the sequence in braces. These groupings are called statement
blocks.
Categories of statement:
Assignment Statement: here values, sometimes the results of calculations,
are stored in variables.
Input/Output statement: here the data is read in or printed out.
Control Statement: through which the program makes a decision about
what to do next.
C has two types of Control structures: selection (decision) and repetition
(loop).
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

127

Selection or Branching statement:


Sometimes it is desirable to alter sequential flow of Control to
provide for a choice of action.
Used to have a program execute different statements
depending on certain conditions. In a sense, makes a program
smarter by allowing different choices to be made.
In C, there are three decision making statements.
1. if execute a statement or not
2. if-else choose to execute one of two statements
3. switch choose to execute one of a number of statements
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

128

Iteration or Loop statements:

A loop is simply a statement or a collection of


statements that is executed repetitively until a
certain condition is reached after which execution
moves to the next executable statement.
In C language, loops are for, while and do-while

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

129

Program control statements

Iteration/Looping

Selection/ Branching

Conditional Type

Unconditional Type

if If-else If-else-if switch

10/11/2012

for

while

Do -while

Goto break continue

Prepared By:Swaminarayan Priya, ISTAR

130

We can specify the condition for selection and


iteration by using relational and logical
operators.
Syntax for writing test condition
Var/exp/const OPERATOR var/exp/const

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

131

Selection Statements

1.
2.
3.

Three versions of selection statements:


One-way decisions using if statement
Two-way decisions using if statement
Multi-way decisions using if statement
The if statement allows branching (decision making) depending
upon a condition. Program code is executed or skipped.
The basic syntax is
if (control expression)
program statement;

If the control expression is TRUE, the body of the if is executed. If


it is FALSE, the body of the if is skipped.
There is no then keyword in C!

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

132

Theses code fragments illustrate some uses of the if


statement
Avoid division by zero
if (x!=0)
y/=x;

Customize output
if (grade>=90)
printf("\nCongratulations!");
printf("\nYour grade is "%d",grade);

Nested ifs
if (letter>='A')
if (letter>='Z')
printf("The letter is a capital \n");
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

133

Write a program that prints the largest among three numbers


#include <stdio.h>
Void main()
{
int a,b,c,max;
printf(enter three values\n);
scanf(%d%d%d,&a,&b,&c);
max = a;
if (max>b)
max=b;
if (max>c)
max=c;
printf(Largest Number is %d,max);
}

10/11/2012

START
PRINT ENTER THREE NUMBERS
INPUT A,B,C
MAX = A
IF B>MAX THEN MAX=B
IF C>MAX THEN MAX=C
PRINT LARGEST NUMBER IS, MAX
STOP

Prepared By:Swaminarayan Priya, ISTAR

134

TWO-WAY DECISIONS USING IF-ELSE STATEMENT


Used to decide between two courses of action.
The syntax of the if-else statement is
if (expression)
statement1;
else
statement2;

If the expression is TRUE, statement1 is executed; statement2 is skipped.


If the expression is FALSE, statement2 is executed; statement1 is skipped.
Some examples
if (x<y)

min=x;
else
min=y;
if (letter == 'e')
++vowel_count;
else
++other_count;
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

135

Write a program in C to check whether a number


given by the user is odd or even
Void main()
{
int n;
printf(enter any number);
scanf(%d,&n);
if (n%2 == 0)
printf(EVEN);
else
printf(ODD);
}

10/11/2012

START
PRINT ENTER ANY NUMBER
INPUT N
IF N/2 (Integer Division)
PRINT EVEN
ELSE
PRINTF ODD
STOP

Prepared By:Swaminarayan Priya, ISTAR

136

Check whether the two given numbers are


equal.
Void main()
{
int a=2, b=3;
if ( a==b)
printf(EQUAL);
else
printf(UNEQUAL);
}

10/11/2012

Void main()
{
int a=2, b=3;
if ( a=b)
printf(EQUAL);
else
printf(UNEQUAL);
}

Prepared By:Swaminarayan Priya, ISTAR

137

Home work: Write a program that determines if a year is leap year


Multi-way decisions
Syntax: if-else-if ladder
If (TestExpr1)
statement1;
else if (TestExpr2)
statement2;
else if (TestExpr3)
statement3;
.
.
else if(TestExprN)
statementN;
else
statementF

As soon as a TRUE control expression is found, the statement associated with it is


executed and the rest of the ladder is bypassed. If no control expressions are
found to be TRUE, the final else statement acts as a default.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

138

For example, consider the following code


if (letter == 'a')
++a_count;
else if (letter == 'e')
++e_count;
else if (letter == 'i')
++i_count;
else if (letter == 'o')
++o_count;
else if (letter == 'u')
++u_count;
else
++const_count;

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

139

Write a program to check whether a number given by


the user is zero, +ve or ve.
Void main()
{
int n;
printf(enter any n);
scanf(%d,&n);
if (n>0)
printf(n is positive);
else
if (n<0)
printf(n is negative);
else
printf(n is zero);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

140

Write a program to display


grade >= 90 then A
grade >= 80 and <90 then B
grade >= 70 and <80 then C
grade >= 60 and <70 then D
else grade is F

10/11/2012

Void main()
{
int score;
char grade;
printf(enter score);
scanf(%d,&score);
if (score >= 90)
grade = A;
else if (score >= 80)
grade = A;
else if (score >= 70)
grade = A;
else if (score >= 60)
grade = A;
else
grade = F;
}

Prepared By:Swaminarayan Priya, ISTAR

141

Write a program to find the largest among three numbers using the nested loop.
Void main()
{
int a,b,c;
printf(enter three numbers);
scanf(%d%d%d,&a,&b,&c);
if (a>b)
if (a>c)
printf(%d,a);
else
printf(%d,c);
else
if (b>c)
printf(%d,b);
else
printf(%d,c);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

142

What will be the output of the following programs?


void main()
{
printf(Hi);
if (-1)
printf(Bye);
}
Hi Bye

10/11/2012

void main()
{
printf(Hi);
if (!1)
printf(Bye);
}
Hi

Prepared By:Swaminarayan Priya, ISTAR

143

void main()
{
float x =199.9;
if (x<100)
printf(One);
if (x < 200)
printf(Two);
if (x < 300)
printf(Three);
}

Two Three

void main()
{
int a=1,b=2,c=3,d=4;
if (d>c)
if (c>b)
printf(%d %d,d,c);
else if (c>a)
printf(%d %d,c,d);
if (c>a)
if (b<a)
printf(%d %d,c,a);
else if (b<c)
printf(%d %d,b,c);
}

4323

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

144

The Conditional Operator


Syntax: expresson1 ? Expression2 : expression3;
It is equivalent to
If (expression1)
Expression2

Else
Expression3;

Find out Maximum from given three numbers m,n and p

Find our maximum from given four numbers using conditional operator:

Int a,b,c,d,e;
e = a>b ? (a>c?(a>d?a:d):(c>d?c:d)):(b>c?(b>d?b:d):(c>d?c:d));

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

145

Switch statement
The switch statement is a better way of writing a program which employs an ifelse ladder.
It is Cs built-in multiple branch decision statement.
The syntax for the switch statement is as follows:
switch (integer expression)
{
case constant1: statement1;
break;
case constant2: statement2;
break;
...
default:
statement;
}

The keyword break should be included at the end of each case statement. In
general, whenever a break statement is encountered in C, it interrupts the normal
flow of control.
In the switch statement, it causes an exit from the switch shunt. The default
clause is optional. The right brace at the end marks the end of switch statement.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

146

The biggest defect in the switch statement is that cases do


not break automatically after the execution of the
corresponding statement list for the case label. Once the
statement list under a case is executed, the flow of control
continues down executing all the following cases until a break
statement is reached.
The break statement must be used within each case if one
does not want the following cases to execute once one case is
selected.
When the break statement is executed within a switch, C
executes the next statement outside the switch statement.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

147

Switch (ch)
{
case A: printf(You entered an A);
break;
case B: printf(You entered an B);
break;
default: printf(Illegal entry);
break;
}

In case, choice may be integer or


character.

Switch (choice)
{
case 1: printf(You entered choice #1);
break;
case 2: printf(You entered choice #2);
break;
default: printf(Illegal entry);
break;
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

148

Switch (donationLevel)
{
case 1: printf(You donated over Rs. 1000);
break;
case 2: printf(You donated over Rs. 500);
break;
case 3: printf(You donated over R5. 250);
break;
A set of statements to
case 4: printf(You donated over R5. 100);
execute can be grouped
break;
default: printf(Pls be a little more generous);
with more than one value of
break;
the variable as in the
Switch
(number)
}
following example.
{
case 1:
case 3:
case 5:
case 7:
case 9: printf( %d is an odd number., number);
break;
case 2:
case 4:
case 6:
case 8: printf( %d is an odd number., number);
break;
default: printf(%d is a value not between or including 1 and 9,number);
break;
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

149

Expression that follows the keyboard switch must evaluate to


an integer or character, which is of integer type itself.
The expression followed by each case must be a constant
expression.
No two case contents can be the same.
The default is optional.
Switch statement can include at most one default label. It may
be coded anywhere but traditionally coded at the end.
A C compiler must permit at least 257 case labels for a switch
statement.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

150

switch (grade)
{
default:
printf("F\n");
break;
case 1:
printf("A\n");
break;
case 2:
printf("B\n");
break;
case 3:
printf("C\n");
break;
case 4:
printf("D\n");
break;
}

10/11/2012

Note: The default is optional. It


can be anywhere in the
switch statement

Prepared By:Swaminarayan Priya, ISTAR

151

Write a program using a switch statement to check


whether a number given by the user is odd or even.
Void main()
{
printf(enter the number);
scanf(%d,&n);
switch (n%2)
{
case 0: printf(\n EVEN);
break;
case 1: printf(\n ODD);
break;
}
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

152

Write a program to carry out the arithmetic operations addition, subtraction,


multiplication and division between two variables.
Void main()
{
char op;
float n1,n2;
printf(Enter two numbers);
scanf(%f %f %c,&n1,&n2,&op);
switch(op)
{
case +: printf(%f\n,n1+n2);
break;
case -: printf(%f\n,n1-n2);
break;
case *: printf(%f\n,n1*n2);
break;
case /: if (n2 == 0)
printf(division by zero error);
else
printf(%f\n,n1/n2);
break;
default: printf(Unknown Operator\n);
break;
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

153

Write a program that checks whether a character


entered by the user is a vowel or not.
Void main()
{
char ch;
printf(Enter a character);
scanf(%c,&ch);
switch(ch)
{
case a:
case A:
case e:
case E:
case i:
case I:
case o:
case O:
case u:
case U:
printf(%c is a vowel,ch);
break;
default:
printf(%c is not a vowel\n);
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

154

What will be the output of following code.


Char ch=Y;
Switch (ch)
{
case Y: printf(Yes/No);
case N: printf(No/Yes);
break;
default: printf(Other);

}
Yes/No No/Yes

10/11/2012

Int ch = 3;
Switch (ch)
{
default: printf(Default);
case 1: printf(Choice1);
break;
case 2: printf(Choice2);
break;
}
Default

Prepared By:Swaminarayan Priya, ISTAR

155

Iteration and repetitive execution


Program looping is often desirable in coding in any language to
have the ability to repeat a block of statements a number of
times.
In C, there are statements that allow iteration of this type.
Specifically, there are two classes of program loops -unconditional and conditional.
An unconditional loop is repeated a set number of times.
In a conditional loop the iterations are halted when a certain
condition is true. Thus the actual number of iterations
performed can vary each time the loop is executed.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

156

Iteration and repetitive execution


The for loop is Cs form of an unconditional loop. The basic syntax of the
for statement is,
for (initialization expression; test expr; increment expr)
program statement;
Here is an example
sum=0;
for (i=0; i<6; ++i)
Sum = sum+i;

The operation for the loop is as follows


1) The initialization expression is evaluated.
2) The test expression is evaluated. If it is TRUE, body of the loop is
executed. If it is FALSE, exit the for loop.
3) Assume test expression is TRUE. Execute the program statements making
up the body of the loop.
4) Evaluate the increment expression and return to step 2.
5) When test expression is FALSE, exit loop and move on to next line of
code.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

157

Sample Loop:
We can trace the execution of the sample loop as follows
sum = 10;
for (i=0; i<6; ++i)
sum=sum+i;

Iteration
1st
2nd
3rd
4th
5th
6th
7th

10/11/2012

I
0
1
2
3
4
5
6

i<6
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE

sum
10
11
13
16
20
25
25

Prepared By:Swaminarayan Priya, ISTAR

158

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

159

Flowchart for FOR loop

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

160

Some general comments regarding the use of the for statement:


Control expressions are separated by ; not ,
If there are multiple C statements that make up the loop body,
enclose them in brackets (USE INDENTATION FOR READABILITY)
for (x=100; x!=65; x-=5)
{
z=sqrt(x);

printf("The square root of %d is %f\n",x,z);


}

Control expressions can be any valid expression. Dont necessarily


have to perform initialization, testing, and incrementation.
Any of the control expressions can be omitted (but always need the
two semicolons for syntax sake).
product=1;
for (i=1;i<=6;)
product*=i++;
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

161

Some general comments regarding the use of


the for statement:
Since test performed at beginning of loop, body
may never get executed
x=10;
for (y=10;y!=x;++y)
printf ("%d",y);

Can string together multiple expressions in the


for statement by separating them by commas
for (x=1,y=5;x+y<100;++x)
z=x%y;

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

162

Write a program to generate following patterns.


If input = 3
Output:
1
2 2
3 3
3
Void main()
{
int n,i,j;
printf(enter n);
scanf(%d,&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
printf(%3d,j);
}
printf(\n);
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

163

Write a program to generate following patterns.


If input = 3
Output:
1
2 3
4 5
6
Void main()
{
int n,i,j,k=1;
printf(enter n);
scanf(%d,&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
printf(%3d,k++);
}
printf(\n);
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

164

Write a program to generate following


patterns.

input n=3
output
1
1 2
1 2 3

10/11/2012

#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,n;
clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}
}
Prepared By:Swaminarayan Priya, ISTAR

165

Write a program to generate following pattern.


input n=3
output
void main()
1 1 1
{
2 2
int i,j,n,k=1;
3

clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=n;i>=1;i--)
{
for (j=1;j<=i;j++)
printf("%3d",k);
k++;
printf("\n");
}
getch();
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

166

Write a program to generate following pattern.


input n=3
output
void main()
1 2 3
{
1 2
int i,j,n,k=1;
1

clrscr();
printf("enterr n");
scanf("%d",&n);
for (i=n;i>=1;i--)
{
k = 1;
for (j=1;j<=i;j++)
printf("%3d",k++);
printf("\n");
}
getch();
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

167

Input = 3 then
Output =
A
B C
D E F

Input = 4 then
Output =
z
z y
z y x
z y x w

Input = 3 then
Output =
Input = 4 then
Output =

A
B A
C B A

****
*
*
*
*
****

Input = 3 then
Output =
A
B C
D E F

Input = 3 then Output =


1
2 2
3 3 3
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

Input = 3 then
Output =
*
* *
* * *

168

Input = 3 then
Output =
A
B C
D E F

10/11/2012

void main()
{
int i,j,k,n;
char ch='A';
clrscr();
printf("enmter amu n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
printf("%3c",ch);
ch++;
}
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR

169

Input = 3 then
Output =
A
B A
C B A

10/11/2012

void main()
{
int i,j,k,n;
char ch='A',ch1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
ch1 = ch;
for (j=1;j<=i;j++)
{
printf("%3c",ch1);
ch1--;
}
ch++;
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR

170

Input = 4 then
Output =
z
z y
z y x
z y x w

10/11/2012

void main()
{
int i,j,k,n;
char ch='z',ch1;
clrscr();
printf("enter any number");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
ch = 'z';
for (j=1;j<=i;j++)
{
printf("%3c",ch);
ch--;
}
printf("\n");
}
getch();
} By:Swaminarayan Priya, ISTAR
Prepared

171

1
2

/*
Input = 3 then Output =
1
2 2
3 3 3
*/

10/11/2012

void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enter any number");
scanf("%d",&n);
sp = n;
for (i=1;i<=n;i++)
{
for (l = 1; l <= sp; l++)
printf(" ");
sp--;
for (j=1;j<=i;j++)
printf("%2d",k);
k++;
printf("\n");
}
getch();
}
Prepared By:Swaminarayan Priya, ISTAR

173

Input = 3 then
Output =
*
* *
* * *

10/11/2012

void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
sp = n;
for (i=1;i<=n;i++)
{
for (l = 1; l <= sp; l++)
printf(" ");
sp--;
for (j=1;j<=i;j++)
printf(" *");
printf("\n");
}
getch();
} Prepared By:Swaminarayan Priya, ISTAR

174

void main()
{
int i,j,k,n,l,sp;
k = 1;
clrscr();
printf("enmter amu n");
scanf("%d",&n);
sp = n-2;

Input = 4 then
Output =
****
*
*
*
*
****

10/11/2012

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


{
for (j = 1; j <= n; j++)
{
if ((i == 1) || ( i == n))
{
printf("*");
}
else
{
printf("*");
for (k = 1; k <= sp; k++)
printf(" ");
printf("*");
break;
}
}
printf("\n");
}
getch(); Prepared By:Swaminarayan Priya, ISTAR

175

while Loop
The while loop provides a mechanism for repeating C
statements while a condition is true.
Its format is
while(control expression)
program statement;
The while statement works as follows:
1) Control expression is evaluated (entry condition)
2) If it is FALSE, skip over the loop.
3) If it is TRUE, loop body is executed.
4) Go back to step 1
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

176

Example while loop


i=1; factorial=1;
while (i<=n)
{
factorial *= i;
i=i+1;

Programmer is responsible for initialization and incrementation.


At some point in the body of the loop, the control expression must
be altered in order to allow the loop to finish. Otherwise: infinite
loop.

Will this loop end?


j=15;
while (j--)
;

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

177

Write a while loop that accepts input from the keyboard until a
negative number is entered and find average of all entered
numbers.
Void main()
{
int x = 1;
int cnt = 0,sum=0;
float avg=0;
while ( x>= 0)
{
scanf(%d,&x);
cnt = cnt + 1;
sum = sum + x;
}
avg = sum / cnt;
printf(Average value = %f,avg);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

178

Write a program to find sum of digits


Void main()
{
int no,r,sum=0;
printf(enter any number\n);
scanf(%d,&no);
while ( no>0)
{
r = no % 10;
sum = sum + r;
no = no / 10;
}
printf(sum of digits %d,sum);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

179

What will be the output of the following code


Void main()
{
int c = 5;
while (c)
{
printf(\t %d,c);
c--;
}
}

Void main()
{
while (1)
{
printf(\t ISTAR);
}
}

10/11/2012

Void main()
{
int c = 5;
while (c)
{
printf(\t %d,c);
c = c - 2;
}
}

Void main()
{
while (0)
{
printf(\t ISTAR);
}
}

Prepared By:Swaminarayan Priya, ISTAR

180

Print the sum of the series 1+2+3+.. Up to n terms


Void main()
{
int c, sum = 0, n;
printf(enter the no.of
terms\n);
scanf(%d,&n);
for (c=1;c<=n;c++)
{
sum = sum + c;
}
printf(Result = %d,sum);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

181

What will be the output of following code


Void main()
{
int c;
for (c=0;c++;c++)
printf(%d,c);
}
Void main()
{
int c;
for (c=1;c<=5;)
printf(%d,c++);
}
10/11/2012

Void main()
{
int c;
for (c=0;++c;++c)
printf(%d,c);
}

Void main()
{
for (;;)
printf(ISTAR");
}

Void main()
{
int c;
for (c=1;c<=5;)
printf(%d,++c);
}
Prepared By:Swaminarayan Priya, ISTAR

182

Is there any difference between the


following for statements?

For(x =1; x <100;x++)


For(x=1; x <100; ++x)
For (x=1; x<100; x = x+1)
For (x=1; x<100; x+=1)
All for loops are same

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

183

What would be the output from the given program?


Void main()
{
int i=9;
for (i--; i--; i--)
printf(%d,i);
}

Void main()
{
int i=9;
for (i--; i--; i--)
printf(%d,i);
}

7531

6 4 2

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

184

Void main()
{
for (;printf(C););
}

It is an infinite loop and it


will repeatedly print C

10/11/2012

Void main()
{
int I;
for (i=5;--i;)
printf(%d,i);
}
4 3 2 1

Prepared By:Swaminarayan Priya, ISTAR

185

Void main()
{
int I =3;
for (i--; i<7; i=7)
printf(%d,i++)
}
2

10/11/2012

Void main()
{
int I;
for (i=-10;!i; i++)
printf(%d,-i);
}

No output

Prepared By:Swaminarayan Priya, ISTAR

186

Do While Statement
The do while statement is a variant of the while statement in which the
condition test is performed at the bottom of the loop. This guarantees that
the loop is executed at least once.
The syntax of the do while statement is
do
{
program statement;
} while (control expression);
and it works as follows
1) The body of the loop is executed.
2) The control expression is evaluated (exit condition).
3) If it is TRUE, go back to step 1. If it is FALSE, exit loop.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

187

Flowchart of Do While statement

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

188

Void main()
{
int c=5;
while (c<5)
{
printf(Hello);
c++;
}
}
No output

Void main()
{
int c=5;
do
{
printf(Hello);
c++;
} while (c<5);
}
Hello

Note: a do-while loop will execute at least once because its test expression is placed at
the end of the loop.
While statement is pre-test loop and do-while is post-test loop.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

189

Pre-test loop

Post-test loop

Initialization

Once

Once

No. of tests

N+1

Actions executed

Updating executed

Minimum iteration

Not even once

At least once

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

190

How many times will the


following while-loop
repeat?
Int i=5;
While (i-- > 0)
printf(X);
5
What does the following
do-while loop print ?
Int I = 0;
Char c = 0;
Do
{
putchar(c+i);
++I;
} While (I < 5);
01234

10/11/2012

How many X are printed by


the following code?
Int I = 5;
While (i-- > 0)
printf(X);
Printf(X);
6
What does the following
while loop print ?
Float s=1.0;
Int a = 4;
While (a<=10)
{
s = a*1.2;
printf(%f,s);
}
}
It never ends becoz a is always 4

Prepared By:Swaminarayan Priya, ISTAR

191

#define infiniteloop while(1)


Void main()
{
infiniteloop;
printf(DONE);
}

None becoz the infiniteloop in main ends


with ;. So loop will reach an end, and
DONE will not print

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

192

The while and for constructs are pre-test loops and the do-while
construct is post-test loop.
The while and do-while loops are event-controlled whereas the for
loop is counter-controlled.
The for loop is appropriate when one knows in advance how many
times the loop will be executed. The while and do-while loops are
used when it is not known in advance when the loop should
terminate.

Write differences between Do-while and while loop.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

193

Goto statement
It is another type of control statement supported by C.
The control is unconditionally transferred to the statement
associated with the label specified in the goto statement.
Syntax: goto Label_name
If an active block is exited using a goto statement, all local variables
are destroyed when control is transferred from that block.
int main()
{
Int n,c;
Long int f =1;
Printf(enter any number);
Scanf(%d,&n);
If (n < 0)
Goto end;

For (c=1; c<=n;c++)


f*=c;
Printf(Factorial = %ld,f);
End:
return 0;
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

197

Special Control statements


There are certain control statements, which
terminate either a loop or a function.
Return Statement: The return type is used in the
definition of a function to set its returned value
and the return statement is used to terminate
execution of the function.
The return statement has two types:
1. Return with void : syntax- return
2. Return without void: syntax- return expression
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

198

break

The break statement is used in loop constructs such as for, while and do-while,
and switch statement to terminate execution of the loop or switch statement.
Syntax: break;
After a break statement is executed within a loop or a case in a switch statement
execution proceeds to the statement that follows the loop or switch statement.

Void main()
{
int c=1;
while (c<=5)
{
if (c==3)
break;
printf(\t %dc);
c++;
}
}
1 2 instead of 1 2 3 4 5
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

199

Void main()
{
int c=1;
while (1)
{
printf(\t %d,c);
c++;
}
}

1 2 3 4 5
10/11/2012

Void main()
{
int c=1;
while (1)
{
if (c==5)
break;
printf(\t %d,c);
c++;
}
}

1 2 3 4
Prepared By:Swaminarayan Priya, ISTAR

200

Write a program to check whether a number is a


prime or not.
Void main()
{
int n,flag = 1;
printf(enter any number);
scanf(%d,&n);
for (i=2; i<n;i++)
{
if (n%i ==0)
{
flag = 0;
break;
}
}
if (flag ==1)
printf(entered number is prime);
else
printf(entered number is not prime);

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

201

continue

The continue statement does not terminate the loop but goes to the test
expression in the while and do-while statements and then goes to the updating
expression in a for statement.
Syntax: continue;
Use to skip an iteration
continue; skips rest of innermost loop body, jumping to loop condition

Example: Void main()


{
int c=1;
while (1)
{
if (c==5)
continue;
printf(\t %d,c);
c++;
}
}
1 2 34
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

202

Write differences between break and continue


statement
Break

Continue

It helps to make an earlier exit from the


block where it appears.

It helps in avoiding the remaining


statements in a current iteration of the
loop and continuing with the next
iteration.

It can be used in all control statements


including switch constructs.

It can be used only in loop constructs.

Syntax: break;

Syntax: continue;

Example

Example

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

203

Chapter 5:
Arrays and Strings

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

204

Arrays and Strings


Array is a data structure consisting of an ordered set of data values of the
homogeneous type.
Arrays are a data structure which hold multiple values of the same data
type.
Arrays are an example of a structured variable in which
1) there are a number of pieces of data contained in the variable name, and
2) there is an ordered method for extracting individual data items from the
whole.
Consider the case where a programmer needs to keep track of the ID
numbers of people within an organization. Her first approach might be to
create a specific variable for each user.
This might look like
int id1 = 101; int id2 = 232; int id3 = 231;
It becomes increasingly more difficult to keep track of the IDs as the
number of variables increase. Arrays offer a solution to this problem.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

205

An array is a multi-element box, a bit like a filing cabinet, and uses


an indexing system to find each variable stored within it. In C,
indexing starts at zero. Arrays, like other variables in C, must be
declared before they can be used.
The replacement of the previous example using an array looks like
this:
int id[3]; /* declaration of array id */
id[0] = 101;
id[1] = 232;
id[2] = 231;
In the first line, we declared an array called id, which has space for
three integer variables. Each piece of data in an array is called an
element. Thus, array id has three elements. After the first line,
each element of id is initialized with an ID number.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

206

The syntax for an element of an array called a is


a[i].
where i is called the index of the array element. The
array element id[1] is just like any normal integer
variable and can be treated as such.
In memory, one can picture the array id as in the
following diagram:
id

101

232

id[0]
10/11/2012

id[1]

Prepared By:Swaminarayan Priya, ISTAR

231

id[2]
207

Declaring Arrays
Arrays may consist of any of the valid data types. Arrays
are declared along with all other variables in the
declaration section of the program and the following
syntax is used
type array_name[n];
where n is the number of elements in the array.

Some examples are


int final[160];
float distance[66];
During declaration consecutive memory locations are
reserved for the array and all its elements. After the
declaration, you cannot assume that the elements have
been initialized to zero. Random junk is at each
elements memory.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

208

Initializing Arrays during Declaration


If the declaration of an array is preceded by the word static, then the array can be
initialized at declaration. The initial values are enclosed in braces. e.g.,

static int value[9] = {1,2,3,4,5,6,7,8,9};


static float height[5]={6.0,7.3,2.2,3.6,19.8};

Some rules to remember when initializing during declaration


1. If the list of initial elements is shorter than the number of array elements, the
remaining elements are initialized to zero. Int a[5] = {1,2,3} then output = 1 2 3 0
0
2. If a static array is not initialized at declaration manually, its elements are
automatically initialized to zero. Int a[5]; output: 0 0 0 0 0
3. If a static array is declared without a size specification, its size equals the length of
the initialization list.

In the following declaration, a has size 5.


static int a[]={-6,12,18,2,323};
Another method for initialization of array is as follows:
For (i=0;i<5;i++)

10/11/2012

a[i] = 0;

Prepared By:Swaminarayan Priya, ISTAR

209

Using Arrays

A common programming error is out-of-bounds array indexing. Consider the


following code:
int grade[3];
grade[5] = 78;
The result of this mistake is unpredictable and machine and compiler dependent.
You could write over important memory locations, for example. Often run-time
errors result.

Array variables and for loops often work hand-in-hand since the for loop offers a
convenient way to successively access array elements and perform some operation
with them.
Basically, the for loop counter can do double duty and act as an index for the array,
as in the following summation example:
int total=0,i;
int grade[4]={93,94,67,78};
for (i=0; i<4; ++i)
total += grade[i];

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

210

Accessing Array Elements

Int num[10];
Following are the examples
Num [0] = 98;
Num[1] = num[0] 11;
Num[2] = 2 * (num[0] 6)
Num[3] = 79;
Num[4] = (num[2] + num[3] 3) / 2;
Tot = num[0] + num[1]+num[2]+num[3]+num[4]

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

211

Note:
Int a[10];
a = 0; // Invalid statement
Int b[10], a[10];
b = a; // Invalid statement
To increment the ith element the given statement can be used:
Ar[i]++;
Ar[i] += 1;
Ar[i] = ar[i] + 1;
To add n to ith element the following statement may be used.
Ar[i] += n;
Ar[i] = ar[i] + n;
To copy the contents of the ith element to the kth element the
following statement may be written.
Ar[k] = ar[i];

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

212

To copy the contents of one array ar to another array br. It must be


done one by one.
Int ar[10], br[10];
For (int I = 0;i<10; i++)
Br[i] = ar[i];
To exchange the values in ar[i] and ar[k].
Int temp;
Temp = ar[i];
Ar[i] = ar[k];
Ar[k] = temp;
Storing values given by the user in an array:
Int a[10],I;
For (i=0;i<10;i++)
scanf(%d,&a*i+);
For printing the values of array:
For (i=0;i<10;i++)
printf(%d,a*i+);
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

213

Write a program to print numbers that are greater


than the average value.
void main()
{
int a[10];
int i,s=0,avg=0;
printf("enter no");
for (i=0; i <10;i++)
{
scanf("%d",&a[i]);
s = s+a[i];
}
avg = s/10;
printf("Average = %d",avg);
for (i=0; i <10;i++)
{
if (a[i] > avg)
printf("%d\n",a[i]);
}
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

214

Write a program to print Fibonacci series using


an array.
Write a program to search largest number from array

Write a program to search an element within an array

Write a program to search an element within an array

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

215

Strings: One-dimensional Character Array


String is the collection of characters which is ended by special
character (ie NULL character).
The NULL character is represented by \0.
Declaration of String:
Char str[30];
Char text[30];
String Initialization:
Char str*9+ = I like C;
Char str*9+ = ,I, ,l,i,k,e, ,C,\0-;
Note: In first example of initialization, NULL character is not
required.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

216

Printing Strings:
Char s*+ = Hello World;
H E L L O
W
Printf(%s,s);
_-_-_-_-_Hello World
Printf(%20s,s);
Hello World_-_-_-_-_
Printf(%-20s,s);
Hell
Printf(%.4s,s);
Hell-_-_-_-_-_-_-_-_
Printf(%-20.4s,s);
-_-_-_-_-_-_-_-_Hell
Printf(%20.4s,s);

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

O R L D

217

Write a program to find length of string


void main()
{
char s[30];
int i,n=0;
printf("enter string");
gets(s);
for (i=0; s[i] != '\0'; i++)
n++;
printf("length = %d",n);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

218

Write a program to reverse the given string


void main()
{
char s[30];
int i,n=0;
printf("enter string");
gets(s);
for (i=0; s[i] != '\0'; i++)
n++;
printf("length = %d",n);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

219

Write a program to check whether the given string is palindrome or not?


void main()
{
char s[30],r[30];
int i,n=0,k=0,flag=0;;
clrscr();
printf("enter string");
gets(s);
for (i=0; s[i] != '\0'; i++)
n++;
for (i=n-1; i>=0; i--)
{
r[k] = s[i];
k++;
}
r[k] = '\0';
10/11/2012

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


{
if (s[i] == r[i])
flag++;
else
break;
}
if (flag == n)
printf("Palindrom");
Else
printf("Not Palindrom\n");
puts(r);
printf("length = %d",n);
getch();
}

Prepared By:Swaminarayan Priya, ISTAR

220

Write a program to convert given string into upper case.


void main()
{
char s[30];
int i,n=0;
printf("enter string");
gets(s);
for (i=0; s[i] != '\0'; i++)
{
if ((s[i] >= 'a') && (s[i] <= 'z'))
s[i] = s[i] - 32;
}
puts(s);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

221

Write a program to find no. of words in given string


void main()
{
char s[50],t[50];
int i,j,k,words=1;
clrscr();
printf("enter any string");
gets(s);
k = 0;
for (i = 0; s[i] != '\0' ; i++)
{
if ((s[i] == ' ')&&(s[i+1] != ' '))
{
words++;
}
}
puts(s);
printf("no of words = %d",words);
getch();

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

222

To find out total no. of vowels, consonants, digits, blank spaces and special characters
Void main()
{
char s[50];
gets(s);
for (i=0; s*i+ != \0; i++)
{
if ((s*i+ == a) || (s*i+ == e) || i o u A E I O U)
vowels++;
else
if ((s*i+ >= 0) &&(s*i+ <= 9))
digits++;
else
if (s*i+ == )
spaces++;
else
if (s*i+ >= a) && s*i+ <= z) || (s*i+ >= A) && s*i+ <= Z) )
consonants++;
else
spChars++;
}
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

223

Read two strings and copy them into third string


s3 = concat(s1,s2)
Void main()
{
char s1[50],s2[50],s3[50];
int I,k=0;
printf(enter two strings);
gets(s1);
gets(s2);
for (i=0; s1[i+ != \0; i++)
{
s3[k] = s1[i];
k++;
}
for (i=0; s2[i+ != \0; i++)
{
s3[k] = s2[i];
k++;
}
s3*k+ = \0;
puts(s3);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

224

To compare two
strings
Inputs:
Pankaj
Priyank
Output: S1<s2
Inputs:
Pankaj
Pankaj
Output: S1=s2
Inputs:
Priyank
Pragnesh
Output: S1>s2
10/11/2012

void main()
{
char s1[50],s2[50];
int i,j,len=0,k=0,l;
printf("enter two strings");
gets(s1);
gets(s2);
for (i=0;s1[i] != '\0' || s2[i] != '\0'; i++)
{
if (s1[i] == s2[i])
k = 0;
else
{
k = s1[i] - s2[i];
break;
}
}
if (k == 0)
printf("Strings are equal\n");
else
if (k>0)
printf("str1 is graater than str2");
else
printf("str1 < str2");
Prepared By:Swaminarayan
Priya, ISTAR
}

225

Write a program to rotate


given string
input: viraj
output:
viraj
irajv
rajvi
ajvir
viraj

10/11/2012

void main()
{
char s1[50],s2[50];
int i,j,len=0,k=0,l;

printf("enter any string");


gets(s1);
for (i=0;s1[i] != '\0'; i++)
len++;
for (i=0;i<=len;i++)
{
k=0;
for (j=i;j<len;j++)
{
s2[k]=s1[j];
k++;
}
for (l = 0; l<i;l++)
{
s2[k] = s1[l];
k++;
}
s2[k] = '\0';
puts(s2);
Prepared By:Swaminarayan
Priya, ISTAR
}

226

Write a program to convert given string into proper form

void main()
{
char s[50],t[50];
int i,j,k;
printf("enter any string");
gets(s);
// Convert given string into lower case
for (i=0;s[i] != '\0'; i++)
{
if (s[i] >= 'A' && s[i] <= 'Z')
s[i] = s[i] + 32;
}
puts(s);

10/11/2012

// remove additional blank spaces


k = 0;
for (i = 0; s[i] != '\0' ; i++)
{
if (s[i] != ' ')
{
t[k] = s[i];
k++;
}
if ((s[i] == ' ') && (s[i+1] != ' '))
{
t[k] = s[i];
k++;
}
}
t[k] = '\0';
puts(t);
// convert string into proper form
for (i=0; t[i] != '\0' ; i++)
{
if ( i == 0)
t[i] = t[i] - 32;
if (t[i] == ' ')
t[i+1] = t[i+1] - 32;
}
puts(t);
}

Prepared By:Swaminarayan Priya, ISTAR

227

Write a program to convert given string into initial form.


Input: Vikas Pankajkumar Verma
Output: V. P. Verma

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

228

More String Functions


Included in the string.h are several more string-related functions that are
free for you to use. Here is a brief table of some of the more popular ones
Function Operation
Strcat: Appends to a string
Strncat: Appends n characters of string
Strcmp: Compares two strings
Strcmpi: Compares two, strings, non-case sensitive
Strncmp: Compares n characters of two strings
Strcpy: Copies one string to another
Strncpy: Copies n characters of one string to another
Strlen: Finds length of a string
Strchr: Finds first occurrence of a given character
Strrchr: Finds last occurrence of given character in string
Strnset: Sets n characters of string to a given character

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

229

Copying Strings
The strcpy function is one of a set of built-in string handling functions
available for the C programmer to use.
To use these functions be sure to include the string.h header file at the
beginning of your program.
The syntax of strcpy is
strcpy(string1,string2);
When this function executes, string2 is copied into string1 at the
beginning of string1. The previous contents of string1 are overwritten.
In the following code, strcpy is used for string initialization:
#include <string.h>
main () {
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

230

Strncpy: Copies n characters of one string to


another.
Void main()
{
char string[10];
char *str1 = "abcdefghi";
strncpy(string, str1, 3);
string[3] = '\0';
puts(string);
printf("%s\n", string);
}
Output: abc
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

231

strcmp which has this syntax


strcmp(string1,string2);
It returns an integer that is less than zero, equal to zero, or greater than
zero depending on whether string1 is less than, equal to, or greater than
string2.
String comparison is done character by character using the ASCII
numerical code.
Void main()
{
Char s1*10+ = Pragnesh, s2*10+ = Prity;
i = strcmp(s1,s2);

if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");
}
Output: s1 < s2

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

232

Void main()
{
char s1*10+ = PRACHI, s2*10+ = prachi;
i = strcmpi(s1,s2);
if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");

}
Output: s1 == s2

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

233

Void main()
{
char s1*10+ = Prachi, s2*10+ = Prakash;
i = strncmp(s1,s2,3);
if (i==0)
printf("s1 == s2\n");
else
if (i>0)
printf("s1>s2");
else
printf("s1<s2");

}
Output: s1 == s2
Strnicmp it compares first n characters of one string with first n characters of
another string. it also ignores case.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

234

Strcat(): It appends one string to another.


Void main()
{
char s1*10+ = ISTAR, s2*10+ = GTU;
strcat(s1,s2);
puts(s1);
}
Input: s1=ISTRA, s2 = GTU
Output: s1 = ISTARGTU
Strncat(): It appends first n characters of one string to another.
Void main()
{
char s1*10+ = ISTAR, s2*10+ = GTU;
strncat(s1,s2,2);
puts(s1);
}
Input: s1=ISTRA, s2 = GTU
Output: s1 = ISTARGT
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

235

Strchr:Finds first occurrence of a given character from the


string.
Void main()
{
char string[15];
char *ptr, c = 'r';
strcpy(string, "This is a string");
puts(string);
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");

}
The character r is at position 12
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

236

Strrchr:

Finds last occurrence of given character in string.

Void main()
{
char string[15];
char *ptr, c = 'r';
strcpy(string, "This is a string");
puts(string);
ptr = strrchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
}
The character r is at position 12

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

237

Strnset: Sets n characters of string to a given


character
Void main()
{
char string[10];
char *str1 = "abcdefghi";
strnset(str1,*, 3);
puts(string);
}
Output: ***defghi
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

238

Strrev(): It reverses a string.


Void main()
{
char s1*10+ = ISTAR;
strrev(s1);
puts(s1);
}
Input: s1=ISTRA
Output: s1 = ARTSI
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

239

Strupr(): It converts given string into upper case.


Void main()
{
char s1*10+ = ISTAR;
strupr(s1);
puts(s1);
}
Input: s1=IStar
Output: s1 = ISTAR

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

240

Strlwr(): It converts given string into lower case.


Void main()
{
char s1*10+ = ISTAR;
strlwr(s1);
puts(s1);
}
Input: s1=IStar
Output: s1 = istar
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

241

Strdup(): it creates duplicate copy of given string.


#include <alloc.h>
Void main()
{
char *dup_str, *original_str = Vidhi;
dup_str = strdup(original_str);
puts(dup_str);
free(dup_str);
}
Output: Vidhi
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

242

Examples of String Functions


Here are some examples of string functions in
action:
static char s1[]="big sky country";
static char s2[]="blue moon";
static char s3[]="then falls Caesar";
Function Result
strlen(s1) 15 /* e-o-s not counted */
strlen(s2) 9
strcmp(s1,s2) negative number
strcmp(s3,s2) positive number
strcat(s2, tonight) blue moon tonight
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

243

More Character Functions


As with strings, there is a library of functions designed to work with character
variables. The file ctype.h defines additional routines for manipulating
characters. Here is a partial list
Function Operation
isalnum Tests for alphanumeric character
isalpha Tests for alphabetic character
isascii Tests for ASCII character
iscntrl Tests for control character
isdigit Tests for 0 to 9
isgraph Tests for printable character
islower Tests for lowercase character
isprint Tests for printable character
ispunct Tests for punctuation character
isspace Tests for space character
isupper Tests for uppercase character
isxdigit Tests for hexadecimal
toascii Converts character to ASCII code
tolower Converts character to lowercase
toupper Converts character to upper

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

244

Character Functions Example


In the following program, character functions are used to convert a
string to all uppercase characters:
A sample session using this program looks like this:
#include <stdio.h>
#include <ctype.h>
main()
{
char name[80];
int loop;
printf ("Please type in your name\n");
gets(name);
for (loop=0; name[loop] != 0; loop++)
name[loop] = toupper(name[loop]);
printf ("You are %s\n",name);
} peace

Please type in your name


Devarshi SHar
You are DEVARSHI SHAH
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

245

void main()
{
int cnt=0,i,j,k,n;
char s[40];
printf("enter character string\n");
gets(s);
for (i=0;s[i] != '\0'; i++)
{
char t = s[i];
cnt = 0;
if (s[i] != '$')
{
for (j = i; s[j] != '\0'; j++)
{
if (t == s[j])
{

Find out
frequency of
each letter in a
string.

cnt++;
s[j] = '$';
}
}
printf("frequency of %c = %d\n",t,cnt);
}
}
puts(s);
10/11/2012
}

Prepared By:Swaminarayan Priya, ISTAR

Input:Pankaj Purvi
Output:
Frequency of P = 2
Frequency of a = 2
Frequency of n = 1
Frequency of k = 1
Frequency of j = 1
Frequency of = 1
Frequency of u = 1
Frequency of r = 1
Frequency of v = 1
Frequency of 1 = 1
246

void main()
{
char s[50],sub[50];
Enter two strings, check whether
int i,j,k,cnt;
the 2nd string is substring of 1st
printf("enter string and substring\n");
string or not? If yes then return
gets(s);
its position.
gets(sub);
for (i=0; s[i] != '\0'; i++)
{
if (s[i] == sub[0])
{
j = i;
Input:Pankaj vidhi purvi ansh
for (k = 0; sub[k] != '\0'; k++)
Substing = vidhi
{
Output: 2nd sting is found in 1st
if (s[i] == sub[k])
string and its position is 7
{
i++;
cnt=0;
}
else
{
cnt = 1;
break;
}
}
if (cnt == 0)
break;
}
}
if (cnt == 0)
and itsBy:Swaminarayan
position is %d",j);Priya, ISTAR
10/11/2012printf("2nd string is found in 1st string
Prepared
247
}

Multi-Dimensional Arrays
Multi-dimensional arrays have two or more index
values which are used to specify a particular element in
the array. For this 2D array element, image[i][j]
the first index value i specifies a row index, while j
specifies a column index.
Declaring multi-dimensional arrays is similar to the 1D
case:
int a[10]; /* declare 1D array */
float b[3][5]; /* declare 2D array */
double c[6][4][2]; /* declare 3D array */
Note that it is quite easy to allocate a large chunk of
consecutive memory with multi-dimensional arrays.
Array c contains 6x4x2=48 doubles.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

248

Initialization of 2-D array:


static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
Int b[3][5] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
Int s[][2] = { 1,1,
2,4,
3,9,
4,16,
};
How to access 2-D array
For (i=0;i<2;i++)
{
for (j = 0; j < 13; j++)
scanf(%d,&daytab[i][j]);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

249

Using Scanset
The scanset conversion facility provided by scanf() is a useful string input
method.
This conversion facility allows the programmer to specify the set of
characters that are (or are not) acceptable as part of the string.
A scanset conversion consists of a list of acceptable characters enclosed
within square brackets.
A range of characters may be specified using notations such as a-z,
meaning all characters within this range.
If an actual - is required in the scanset, it must be the first or last
character in the set.
If the first character after the * is a ^ character, then the rest of the
scanset specifies unacceptable characters rather than acceptable
characters.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

250

main)()
{
char s[50];
printf(enter a string in lower case\n);
scanf(%*a-z+,s);
printf(The string was : %s,s);
}
Input: hello world
Output: hello world
Input: hello, world
Output: hello
Input: hello1234
Output: hello

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

251

Single-line input using scanset with ^


The ^ plays an important role while taking input.
For a single-line text input, the user press <Return> or <Enter> key to
terminate the string.
Void main()
{
char s[100];
printf(enter string);
scanf(%*^\n+,s);
puts(s);
}
Input: Hello How r u
Output: Hello How r u

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

252

Multiline input using scanset


Void main()
{
char s[100];
printf(enter a string, terminate with a ~ sign);
scanf(%*^~+,s);
printf(%s,s);
}
Input: I am a student of MCA-1 ~
Output: I am a student of MCA-1
Note: the terminating character is not included in string but it stays in the
read buffer and it will be picked by the next call to scanf() statement.
Void main()
{
char s[100],x;
printf(enter a string, terminate with a ~ sign);
scanf(%*^~+,s);
Input:I am a student of MCA-1 ~
scanf(%c,&x);
Output: s = I am a student of MCAprintf(%s,s);
1
putchar(x);
X =~
} 10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
253

String input and output using fscanf() and fprintf()


Each C program has three I/O streams: Stdin,stdout and stderr
The input stream is called standard-input (stdin).
The usual output stream is called standard-output (stdout)
The side stream of output characters for errors is called standard-errror
(stderr).
Void main()
{
int first,second;
fprintf(stdout,enter two numbers);
fscanf(stdin,,%d %d,&first,&second);
fprintf(stdout,sum of two numbers = %d,f+s);
}
Input: 10 20
Output: sum of two numbers = 30

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

254

Write a program to find transpose of matrix


Void main()
{
int m[10][10],t[10][10];
Matrix addition and subtraction
int rows,cols;
printf(enter no of rows and cols);
scanf(%d%d,&rows,&cols);
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
scanf(%d,&m*i+*j+);
}
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
t[i][j] = m[i][j]);
}
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
printf(%d,t*i+*j+);
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

255

Array of strings: 2-D Character Array


A 2-D array of strings can be declared as follows:
<data_type><string_array_name>[<row_size>][<col_size>]
For eg. S[5][30];
Initialization:
Char s*5+*30+ = ,red,pink,blue,yellow,black-;
R

\0

\0

\0

\0

\0

Here every row is a string. Following declarations are invalid.


Char s*5+*+ = ,red,pink,blue,yellow,black-;
Char s*+*+ = ,red,pink,blue,yellow,black-;
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

256

Manipulating String Arrays


Void main()
{
char s[5][30];
int I;
printf(enter any five stings\n);
for (I=0;I<5;I++)
gets(s[i]);
printf(Final Output\n);
for (I=0;I<5;I++)
puts(s[i]);
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

Input:
Ravi
Yagnesh
Payal
Pankaj
Viraj
Output:
Ravi
Yagnesh
Payal
Pankaj
Viraj

257

Write a program to sort an array of strings.


Input: Pankaj Anil Anant Pragnesh Prakash
Output: Anant Anil Pankaj Pragnesh Prakash
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char s[5][50];
char t[50];
int i,j,k,n;
clrscr();
printf("enter name");
for (i=0;i<5;i++)
gets(s[i]);
printf("entered strings are as follows\n");
printf("enter Mr. for male and Ms. for female\n");
for (i=0; i<5;i++)
puts(s[i]);

10/11/2012

for (i=0; i<5;i++)


{
for (j=0;j<5;j++)
{
if (strcmp(s[i],s[j]) < 0)
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
}
}
printf("Output \n");
for (i=0;i<5;i++)
puts(s[i]);
getch();
}

Prepared By:Swaminarayan Priya, ISTAR

258

Write a program to convert girls name into capital


letters and boys name into lower case.
Input:
Mr.Prakash
Ms.Priyanka
Mr.Yagnseh
Ms.Payal
Ms.Neelam

Output
Mr.Prakash
MS.PRIYANKA
Mr.Yagnseh
MS.PAYAL
MS.NEELAM

void main()
{
char s[5][50];
char t[50];
int i,j,k,n;
clrscr();
printf("enter name");
for (i=0;i<5;i++)
gets(s[i]);
10/11/2012

for (i=0; i<5;i++)


{
strncpy(t,s[i],2);
t[2] = '\0';
puts(t);
if (strcmp(t,"Mr") == 0)
strlwr(s[i]);
else
strupr(s[i]);
}
for(i=0;i<5;i++)
puts(s[i]);
}

Prepared By:Swaminarayan Priya, ISTAR

259

Check for syntax error of the following declarations:


1) char str*10+ = ISTAR;
2) char str*10+ = ,G,T,U,\0-;
3) char s1*+ = CVM;
4) char s2*+ = Charutar Vidya Mandal;
5) int a[][2] = {1,1,2,2,3,3,4,4};
6) int x[4][2] = {{1,2},{3,4},{5,6}};
7) int x[4][2] = {1,2,3,4,5,6};
8) char s*5+*+ = ,Pinal,Pragnesh,Prity,Payal,Pranav-;
9) char s*+*+ = ,Pinal,Pragnesh,Prity,Payal,Pranav-;

What will be the output of the following code:


void main()
{
char s*2+*5+ = ,EVEN,ODD-;
int n;
printf(Enter any number);
scanf(%d,&n);
printf(The number is %s,s*n%2+);
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

260

Multiple-choice questions:
1. Arrays declared as static contain an initial value which is (A) 10 (B) 1 (C) 0
(D) None of these
2. An integer array of 10 elements occupies (a) 10 bytes (b) 20 bytes (c) 40
bytes (d) none of these
3. A string is a character array terminated by (a) z (b) zero (c) NULL
character (d) none of these
4. The subscript of an array in C language starts from (a) -1 (b) 1 (c) 0 (d)
user defined
5. Arrays, by default, contain (a) -1 (b) garbage value (c) zero (d) none of
these

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

261

Fill in the blanks:


1. In an array int s[5], the letter s contains the
________ of the array
2. In an array the subscript 4, actually contains
the _____ element of the array.
3. A 2-D array is stored in the form of
_________ array in the memory.
4. A 2-D array is also called a ________
5. A 2-D character array is also known as
______.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

262

What will be the output of the following code:


Main()
{
char a*5*2/2+ = ,a,e,I,o,u-
printf(%d,a[-3]);
}
Main()
{
char a[];
a*0+ = A;
printf(%c,a[0]);
}
Main()
{
static char city*30+ = Bombay;
int I = 0;
while (i[city])

10/11/2012

Printf(%c,city[i++]);
Prepared By:Swaminarayan Priya, ISTAR

263

Chapter 6:
Functions

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

264

Functions
A function in C is a small sub-program that performs a particular
task, and supports the concept of modular programming design
techniques.
In modular programming the various tasks that your overall
program must accomplish are assigned to individual functions and
the main program basically calls these functions in a certain order.
C language supports two types of functions: Library functions and
user defined function.
Library Function: They are written by system. And they are used to
carry out a no. of commonly used operations or calculations.
For eg. String functions
Maths Functions
File handling functions

User defined Functions:


They are written by programmer to perform various individual task.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

265

Characteristics of functions
Any C program contains at least one function.
If a program contains only one function, it must be main() function.
If a program contains more than one function, then one function
must be main() function because execution of program always start
from main() function.
There is no limit on no. of functions in a program.
Nested function is also allowed.
A same function can be any no. of times.
A function call to itself , which is known as Recursion.
Any function can be called from any other function. Even main()
function can be called from other function.
A function can be called from other function but a function can not
be defined in another function.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

266

Advantages of Functions
Code reuse: It avoids repetitive works.
Easy to debug. Get one function working well then move on to the
others.
Easy to modify and expand. Just add more functions to extend program
capability
Function portability: useful functions can be used in a number of
programs.
Data Protection: Functions can be used to protect data. This is related
to with the concept of local data. Local data is the data described
within a function. They are available only within a function when the
function is being executed.
Programmer can also build a customized library of frequently used
functions.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

267

In order to use functions, the programmer must do three


things
Define the function
Declare the function
Use the function in the main code.

The declaration statement that identifies a function with a


name, list of arguments and the type of data returned.
The function definition that consists of a function header
identifying the function followed by the body of the function
containing the executable code for the function.
The calling statement that invokes the function by either
passing or not passing some parameters.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

268

Function Definition
The function definition is the C code that implements what the
function does.
Function definitions have the following syntax
return_type function name (data type variable name list)
{
local declarations;
function statements;
}
where the return_type in the header tells the type of the value
returned by the function (default is int)
Where the data type variable name list tells what arguments the
function needs when it is called (and what their types are).
where local declarations in the function body are local constants
and variables the function needs for its calculations.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

269

Function Definition Example 1


Here is an example of a function that calculates
n!
int factorial (int n)
{
int i,product=1;
for (i=2; i<=n; ++i)
product *= i;
return product;
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

270

Function Definition Example 2


Some functions will not actually return a value or need any
arguments. For these functions the keyword void is used.
Here is an example:
void write_header(void) {
printf("Navier-Stokes Equations Solver ");
printf("v3.45\n");
printf("Last Modified: ");
printf("12/04/95 - viscous coefficient added\n");
}

The 1st void keyword indicates that no value will be returned.


The 2nd void keyword indicates that no arguments are needed for
the function.
This makes sense because all this function does is print out a
header statement.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

271

return Statement
A function returns a value to the calling program with the use of the
keyword return, followed by a data variable or constant value. The
return statement can even contain an expression. Some examples
return 3;
return n;
return ++a;
return (a*b);
When a return is encountered the following events occur:
1 execution of the function is terminated and control is passed back to
the calling program, and
2 the function call evaluates to the value of the return expression.
If there is no return statement control is passed back when the
closing brace of the function is encountered (falling off the end).
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

272

return Statement Examples


The data type of the return expression must match that of the declared
return_type for the function.
float add_numbers (float n1, float n2)
{
return n1 + n2; /*legal*/
return 6; /*illegal, not the same data type*/
return 6.0; /*legal*/
}

It is possible for a function to have multiple return statements.


For example:
double absolute(double x)
{
if (x>=0.0)
return x;
else
return -x;
}

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

273

Using Functions
How we can invoke the function?
This is the easiest part! To invoke a function, just type its name in your
program and be sure to supply arguments (if necessary). A statement
using our factorial program would look like
number=factorial(3);
To invoke our write_header function, use this statement write_header();
When your program encounters a function invocation, control passes to
the function. When the function is completed, control passes back to the
main program.
In addition, if a value was returned, the function call takes on that return
value. In the above example, upon return from the factorial function the
statement
factorial(3) 6 and that integer is assigned to the variable number.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

275

Function Prototype: The declaration of any function is compulsory in C


before it is defined.
The declaration describes the function name, its return value and no. of
parameters , types of parameters and sequence of parameters. The
function prototype allows the compiler to compare the function calls to
the function prototype and to enforce checking.
Function Declaration: It is exactly same as function prototype but scope of
function prototype is global whereas the scope of function declaration is
local.
Function Prototype method is the new method and known as Modern
or ANSI method. And function declaration method is known as Classic
method.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

276

Void display(int x1);


Int sum(int x,int y);
Void main()
{
sum(1,2);
}
Int sum(int x,int y)
{
int res = 0;
res = x + y;
display(res);
return(0);
}
Void display(int x1)
{
printf(sum = %d,x1);
}
10/11/2012

Function prototype

Here, we can use display() and sum() function


anywhere in a program because it is function
prototype and scope of the function
prototype is global.
But if these two functions are declared within
main() function then it is known as function
declaration. Then we can call these two
functions only from the main() function but we
can not call display() function from sum()
function.

Prepared By:Swaminarayan Priya, ISTAR

277

Function Prototype

Function Definition

It is always declare before main() by


function.

It can be defined anywhere in the


program except inside any function

It is ended by semicolon

It must not be ended by semicolon

It does not contains body of the function.

It contains body part of the function.

Definition

Definition

Eg.

Eg.

There is no need to write variable name in Variable names are mandatory.


argument
Int fun(int x,int y)
Int fun(int,int);

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

278

Formal and Actual arguments


Actual parameters: They are the variables
which are defined into the calling program
and they are used to pass value of that
variable into the called function.
Formal Parameters: They are defined in
function and they are used to receive the
value of actual parameters.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

279

Call By Reference & Call By Value


It passes addresses of the parameters instead of its values.
Whenever you use call by reference, then function work on the
original data.
Any changes made by the function on formal parameter also
change the actual parameter in calling program.
Whenever you call any function at that time it passes only value from
the calling function to called function.
The called function creates a new set of variables and copies the
values of arguments into them.
The function does not have access to the actual variable in the calling
program because it works on the copies of values.
After executing any function, the value of actual parameters remains
same in the calling program.
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

280

Call By Reference
Void main()
{
int a=10,b=20;
printf(a=%d b=%d,a,b);
swap(&a,&b);
printf(a=%d b=%d,a,b);
}
Swap (int *m, int *n)
{
int t;
t = *m;
*m = *n;
*n = t;
}
Output: a=10 b = 20
a = 20 b = 10

10/11/2012

Call By Value
Void main()
{
int a=10,b=20;
printf(a=%d b=%d,a,b);
swap(a,b);
printf(a=%d b=%d,a,b);
}
Swap (int m, int n)
{
int t;
t = m;
m = n;
n = t;
}
Output: a=10 b = 20
a = 10 b = 20

Prepared By:Swaminarayan Priya, ISTAR

281

Scope Rules of functions


Local to function:
Void main()
{
int I =20;
display(i);
}
Display(int j)
{
int k = 35;
printf(j = %d,j);
printf(k = %d,k);
}
Output: j=20
k = 35
10/11/2012

Scope of variables are global


int I =20,k = 35;
Void main()
{
printf(i=%d,i);
printf(k=%d,k);
display();
}
Display()
{
printf(i = %d,i);
printf(k = %d,k);
}
Output: i=20
k = 35
i=20
k = 35

Prepared By:Swaminarayan Priya, ISTAR

282

Passing array element to function


Void main()
{
int I;
int a[] = {21,22,23,24,25};
for (i=0;i<5;i++)
display(a[i]);
}
Void display(int m)
{
printf(%3d,m);
}

10/11/2012

Here we are passing an


individual array element at
a time to the function
display() and getting it
printed in the function
display().

Prepared By:Swaminarayan Priya, ISTAR

283

Passing an entire array to function


Void main()
{
int I;
int a[] = {21,22,23,24,25};
display(a,5);
}
Void display(int m[5],int n)
{
for (i=0;i<n;i++)
printf(%3d,m*i+);
}

10/11/2012

Here we are passing an


individual array element at
a time to the function
display() and getting it
printed in the function
display().

Prepared By:Swaminarayan Priya, ISTAR

284

Write a program to find the maximum value in


an array.
Write a program to implement strcpy()
function.
Write a program using a function to perform
addition of two matrices.

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

285

#include <stdio.h>
#include <conio.h>
void read(int x[3][3]);
void print(int x[3][3]);
void add1(int p[3][3],int q[3][3],int r[3][3]);
void main()
{
int a[3][3],b[3][3],c[3][3];
clrscr();
printf("enter value for Matrix A");
read(a);
printf("enter value for Matrix B");
read(b);
add1(a,b,c);
printf("Resultant Matrix\n");
print(c);
getch();
}

10/11/2012

void read(int x[3][3])


{
int i,j,k;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
scanf("%d",&x[i][j]);
}
void print(int x[3][3])
{
int i,j,k;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
printf("%4d",x[i][j]);
printf("\n");
}

Prepared By:Swaminarayan Priya, ISTAR

286

void add1(int p[3][3],int q[3][3],int r[3][3])


{
int i,j,k;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
r[i][j] = p[i][j] + q[i][j];
}
}
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

287

The function arguments may have a combination of arrays


and variables specified in the function declaration.
Float findavg(int num1,float list[10]);
Here the declaration float list[10] implies that list is an array
of elements that contain data of float type. There is also a
variable named num1 that has been used as one of the
function arguments.
Float findavg(int size,float list[]);
Here the declaration float list[] is specified as an array of
elements that contains data of float type. The dimension of
the array
Float findavg(int num1,float *list);
Float findavg(int ,float);

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

288

Scope rules in nested & parallel blocks of a program


void main()
{
In outermost block x=3 y=5 z=7
int x=3,y=5,z=7;
In Inner block1 x=3 y=6 z=8.56
In Inner block2 x=6 y=6 z=6
clrscr();
In inner block 1 after executing block2 x=6 y=6
printf("In outermost block x=%d y=%d z=%d\n",x,y,z);
z=8.56
{
In outermsot block after executing block1 x=6 y=5
int y=6;
z=7
float z=8.56;
printf("In Inner block1 x=%d y=%d z=%f\n",x,y,z);
x = y;
{
int z;
z = y;
printf("In Inner block2 x=%d y=%d z=%d\n",x,y,z);
}
printf("In inner block 1 after executing block2 x=%d y=%d
z=%f\n",x,y,z);
}
printf("In outermsot block after executing block1 x=%d y=%d
z=%d\n",x,y,z);
getch();
}
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

289

1.

Recursion:
Calling a procedure or function to itself is recursion.
e.g. proc f(x)
{
f(x);
}
Recursion is not available in all languages like COBOL, BASIC,
and FORTRAN. So for that, there is one procedure which is
useful to convert the recursion procedure to non-recursion
procedure.
In PASCAL, C, ALGOL-60 recursion is available.
Main characteristics of recursion.
1. Call itself
2. Stopping criteria
Prepared By:Swaminarayan
Priya, ISTAR

290

10/11/2012

Prepared By:Swaminarayan
Priya, ISTAR

291

10/11/2012

Prepared By:Swaminarayan
Priya, ISTAR

292

10/11/2012

#include <stdio.h>
#include <conio.h>
int fact(int n)
{
int t=1;
if (n == 0)
return 1;
else
return(n*fact(n-1));
}
void main()
{
int no;
clrscr();
printf("enter no\n");
scanf("%d",&no);
printf("Fact = %d",fact(no));
getch();
}
10/11/2012

N=3
Fact(3)
3 * fact(2)
3 * 2 * fact(1)
3 * 2 * 1 * fact(0)
3*2*1*1
3*2*1
3*2
6

Prepared By:Swaminarayan Priya, ISTAR

293

#include <stdio.h>
#include <conio.h>
int fib(int val)
Fibonacci sequence for 6
{
terms is 1 1 2 3 5 8
if (val <= 2)
return 1;
else
return(fib(val - 1) + fib(val -2));
}
void main()
{
int n;
clrscr();
printf("enter number\n");
scanf("%d",&n);
printf("Fibonacci sequence for %d term is",n);
for (int j =1; j<=n; ++j)
printf(" %d",fib(j));
getch();
10/11/2012
Prepared By:Swaminarayan Priya, ISTAR
}

295

42 23 74 11 65 58 94 36 99 87
Key

QUICK SORT

If (a(i) < key) then


Give increment to I
Else
start from j variable
if (a(j) > key) then
give decrement to j
If ( i < j )
interchange a(i) and a(j)
If I >= j then
interchange key and a(j)

It divides array into two parts, apply the same procedure on both parts of
array

10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

296

void quick_sort(int list[], int left, int right)


{
int pivot,lft_arrow,rt_arrow;
lft_arrow = left;
rt_arrow = right;
pivot = list[(left+right)/2];
do
{
while (list[rt_arrow] > pivot)
rt_arrow--;
while (list[lft_arrow] < pivot)
lft_arrow++;
if (lft_arrow <= rt_arrow)
{
int t;
t = list[lft_arrow];
list[lft_arrow] = list[rt_arrow];
list[rt_arrow] = t;
lft_arrow++;
rt_arrow--;
}
} while (rt_arrow >= lft_arrow);
if (left < rt_arrow)
quick_sort(list,left,rt_arrow);
if (lft_arrow < right)
quick_sort(list,lft_arrow,right);
}
10/11/2012

void main()
{
int a[10];
printf("enter array elements");
for (int i = 0; i < 10; i++)
scanf("%d",&a[i]);
quick_sort(a,0,9);
for ( i = 0; i < 10; i++)
printf("% d\n",a[i]);
}

Prepared By:Swaminarayan Priya, ISTAR

297

Chapter 7
Pointers in C
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

298

Pointers in C
All the computers have primary memory, also known as RAM. For eg. A
computer may have 16,32,64,128,256 or 512 MB of RAM installed.
RAM holds the programs that the computer is currently running along
with the data they are currently manipulating (their variables and data
structures).
All the variables used in a program reside in the memory when the
program is executed.
There are three areas of memory that have special capabilities assigned by
the compiler and linker.
1. Stack: It is a ordered list of data in which insertion and deletion possible
only from the one end known as top of the stack.
2. Heap: It is a fixed size and used by the system as needed in a random
fashion. Dynamic memory handling functions - alloc() and realloc()
functions fetch free block from heap and free() function returns free
block to heap.
3. Global Memory: This is all the memory on the machine that is not
assigned to the stack or the heap. Generally variables are stored in global
memory. bles
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

299

Chapter 8
User-defined Data Types
and Variables: Structure,
Union, Enumerations, and
Bitfield
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

300

Chapter 9
Files in C
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

301

Chapter 10
Linked Lists
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

302

Chapter 11
Advanced C
10/11/2012

Prepared By:Swaminarayan Priya, ISTAR

303

Вам также может понравиться