0% found this document useful (0 votes)
71 views86 pages

Chapter Eleven

This document discusses programming languages. It begins by defining a programming language as a vocabulary and set of rules for instructing a computer. It describes high-level languages like BASIC, C, and Pascal that are easier for humans than machine language, which uses only numbers. Above high-level languages are 4GLs that are closest to human languages. Programs must eventually be converted to machine language for the computer. The document also discusses different types of programming languages like machine language, assembly language, and high-level languages. It provides examples of commonly used programming languages for different purposes like C++ for game development and SQL for database development.

Uploaded by

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

Chapter Eleven

This document discusses programming languages. It begins by defining a programming language as a vocabulary and set of rules for instructing a computer. It describes high-level languages like BASIC, C, and Pascal that are easier for humans than machine language, which uses only numbers. Above high-level languages are 4GLs that are closest to human languages. Programs must eventually be converted to machine language for the computer. The document also discusses different types of programming languages like machine language, assembly language, and high-level languages. It provides examples of commonly used programming languages for different purposes like C++ for game development and SQL for database development.

Uploaded by

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

Chapter Eleven Programming Language

CHAPTER ELEVEN
PROGRAMMING LANGUAGE

Overview
Programming language is a vocabulary and set of grammatical rules for instructing a computer to
perform specific tasks. The term programming language usually refers to high-level languages, such as
BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal. Each language has a unique set of keywords
(words that it understands) and a special syntax for organizing program instructions.

High-level programming languages, while simple compared to human languages, are more complex
than the languages the computer actually understands, called machine languages. Lying between
machine languages and high-level languages are languages called assembly languages. Assembly
languages are similar to machine languages, but they are much easier to program in because they allow
a programmer to substitute names for numbers. Machine languages consist of numbers only.

Lying above high-level languages are languages called fourth-generation languages (usually
abbreviated 4GL). 4GLs are far removed from machine languages and represent the class of computer
languages closest to human languages.

Regardless of what language you use, you eventually need to convert your program into machine
language so that the computer can understand it. There are two ways to do this:
 compile the program
 interpret the program

The choice of which language to use depends on the type of computer the program is to run on, what
sort of program it is, and the expertise of the programmer.

Learning Objectives
In this chapter you will learn about

 Programming language
 Process to write a Program
 Translator
 Program Design
 Programming Tools
 Overview of C Programming Language
 Basic Structure of C Programs
 Decision Making And Branching
 Decision Making and Looping
 Function
 Structure
 Pointer
 File Management.

Page- 247
Chapter Eleven Programming Language

Program
Program is an organized list of instructions that, when executed, causes the computer to behave in a
predetermined manner. Without programs, computers are useless.
A program is like a recipe. It contains a list of ingredients (called variables) and a list of directions
(called statements) that tell the computer what to do with the variables. The variables can represent
numeric data, text, or graphical images.

Programming language
A programming language is an artificial language designed to communicate instructions to a machine,
particularly a computer. Programming languages can be used to create programs that control the
behavior of a machine and/or to express algorithms precisely.
The earliest programming languages predate the invention of the computer, and were used to direct the
behavior of machines such as Jacquard looms and player pianos. Thousands of different programming
languages have been created, mainly in the computer field, with many more being created every year.
Most programming languages describe computation in an imperative style, i.e., as a sequence of
commands, although some languages, such as those that support functional programming or logic
programming, use alternative forms of description.
A programming language is usually split into the two components of syntax (form) and semantics
(meaning). Some languages are defined by a specification document (for example, the C programming
language is specified by an ISO Standard), while other languages, such as Perl, have a dominant
implementation that is used as a reference.
A programming language consists of all the symbols, characters, and usage rules that permit people to
communicate with computer.

Types of Programming language


There are three types of programming languages are available. They are:
1. Machine Language(Low Level Language)
2. Assembly Language(Symbolic Language)
3. Procedural Language(High level Language)

Fig 11.1: Types of Programming Language


1. Machine Language (Low Level Language)
The language in which binary code is used to write a program is known as Machine Language. The
Computer understands nothing but binary 0 and 1. An instruction prepared in machine language will
have at least two parts: a Operation Code for each of its function like add, multiply etc and the Operand,
which tells the computer where to find or store the data or other instructions that are to be manipulated.
Advantages:
The programs written in machine language can be executed very fast by the computer. This is mainly
because machine instructions are directly understood by the CPU and no translator or compilation of the

Page- 248
Chapter Eleven Programming Language

program is needed. Machine languages make efficient use of storage-language instructions and their
storage in computer memory can be controlled by manipulating the individual bits.
Disadvantages:
 Writing program in machine language is tedious, time-consuming and highly error-
prone.
 Write program in machine language requires a high level of programming skills.
 Machine languages are machine dependent.
 It is difficult to correct or modify machine language programs.

2. Assembly Language
It is the language in which programmer uses some form of names or level to refer to specific storage
locations. Assembly language software first translates the specified operation code symbol and symbols
address into its machine language equivalent, because the only language understood by the machine is
the machine language.

Advantages:
 Operation codes used in machine language are replaced by mnemonics which are
easier to remember.
 It is not required to keep track of memory locations as is required in the machine
language.
 While writing programs in assembly language, fewer errors are made, and those are
easier to find.
 It is easier to modify because of the use of mnemonics are symbolic field names.
 Insertions and deletions in the program are easy.
 The human effort required to write a program is much less as compared to that needed
in writing of a machine language program.
Disadvantages

 An assembly language program cannot be executed on small sized computer.


 Assembly languages are machine dependent as each instruction in the symbolic
language is translated into exactly one machine language.
 Coding in assembly language is time consuming.
3. High Level Language
The language in which symbols and words are similar to those of ordinary arithmetic and English and
are independent of the computer of which the program is to be used, is known as high level language.

Advantages
 High level languages are machine independent
 They are easier to learn than assembly languages
 They require less time to write.
 The writing of program in these languages does not require the knowledge of the
internal structure of a Computer
 They provide better documentation
 They are easy to maintain
 Modifications, if necessary written in these languages are easy and straightforward.

Page- 249
Chapter Eleven Programming Language

Disadvantages
 Lower efficiency: As the programs written in high level languages need a compiler
which is load into the main memory of the computer and, thus, occupies enough of
memory space to take more time to run.
 Lack of Flexibility: Because the automatic features of high level languages always
occur and are not under the control of the programmer, they are less flexible than
assembly language.

Applied Programming Languages


A programming language is a computer language programmers use to develop applications, scripts, or
other set of instructions for a computer to execute. Several programming languages and scripting
languages are given below:
1. Applications and Program development
Application and program development involves programs you work on a daily bases. For example, the
Internet browser you are using to view this web page is considered a program. If you are interested in
writing your own programs you should consider the below languages.
C, C#, C++, D, Java, Tcl, Visual Basic
2. Artificial Intelligence development
Artificial Intelligence or related fields could involve anything from creating the character interactions in
computer games, portions of programs that make the decisions in programs, chat bots, or any other
related programs. If you're interested in writing your own AI you should consider the below languages.
AIML, C, C#, C++, Prolog
3. Database development
Database developers create and maintain databases. If you're interested in creating your own database or
maintaining other databases you should consider any of the below languages.
DBASE, FoxPro, MySQL, SQL, Visual FoxPro
4. Game development
Game development involves the development of computer games or other entertainment software. If
you're interested in writing your own games you should consider the below languages.
C, C#, C++, DarkBASIC, Java
5. Computer drivers or other hardware interface development
Computer drivers and programming hardware interface support is a necessity for computers to operate
with the hardware; without it your computer wouldn't work. If you're interested in writing your own
drivers or software interfaces for hardware devices you should consider the below languages.
Assembly, C
6. Internet and web page development
The Internet and web page development is the essence of the Internet, without developers we would
have no Internet. If you're interested in creating your own web pages, developing Internet applications,
or Internet related tasks, you should consider the below languages.
HDML, HTML, Java, JavaScript, Perl, PHP, XML
7. Script development
Although not likely to be a career, knowing how to create and develop scripts to increase your
productivity or your company's can save you countless hours. If you're interested in developing your
own scripts you should consider the below languages.
awk, bash, Batchfile, Perl, Tcl

Page- 250
Chapter Eleven Programming Language

Process to write a Program

A computer is not intelligent. It cannot


analyze a problem and come up with a
solution. A human (the programmer) must
analyze the problem, develop the
instructions for solving the problem, and
then have the computer carry out the
instructions. What’s the advantage of
using a computer if it cannot solve
problems? Once we have written a
solution for the computer, the computer
can repeat the solution very quickly and
Fig 11.2: Programming Process
consistently, again and again. The computer frees people from repetitive and boring tasks.
To write a program for a computer to follow, we must go through a two-phase process: problem solving
and implementation

Problem-Solving Phase
1. Analysis and Specification. Understand (define) the problem and what the solution must do.
2. General Solution (Algorithm). Specify the required data types and the logical sequences of
steps that solve the problem.
3. Verify. Follow the steps exactly to see if the solution really does solve the problem.

Implementation Phase

1. Concrete Solution (Program). Translate the algorithm (the general solution) into a
programming language.
2. Test. Have the computer follow the instructions. Then manually check the results. If you
find errors, analyze the program and the algorithm to determine the source of the errors, and
then make corrections.
Once a program has been written, it enters a third phase: maintenance.

Maintenance Phase

1. Use. Use the program.


2. Maintain. Modify the program to meet changing requirements or to correct any
errors that show up while using it.

Translator: (Compiler, Interpreter, Assembler)

Translator is a computer program that performs the task of converting a program written in one
programming language into a program in another programming language. Translators of programming
languages are mainly classified into two groups depending on the nature of the source language
accepted by them.

Page- 251
Chapter Eleven Programming Language

Compiler
Compiler is a translator that accepts instructions written in high level language and compiles each
instruction into machine language producing a complete program in machine language known as object
program. This phase is known as compilation phase.
All the testing of the source program as regards the correct format of the instructions is performed at
this stage and errors, if detected, are printed out as messages to the programmer to enable him to correct
his program. The compiler resides on a disc on other mass-storage media. When the compiler is needed,
it is called and is capable of translating source programs written in only one high level language. Thus a
FORTRAN compiler cannot be used to translate a C source program.

Interpreter
Interpreter is one kind of translator that translates and executes each source program statement written
in high level language before translating and executing next one but does not produce an object
program. It translates the source program line by line. If any errors come then it reports to the
programmer and stops its operation. After correcting errors it can resumes its operation.
BASIC, APL, PROLOG and LISP are mainly interpreted languages.

Table 11.1: Differences between Compiler and Interpreter


The differences between Compiler and Interpreter are given below:

Compiler Interpreter
Translates the entire program at a time. Translates the program instruction by instruction.
Requires more main memory Requires less main memory
Converts the entire program to machine code, Each time the program is executed; every
when all the syntax errors are removed, and instruction is checked for syntax and then
executes the object code directly. converted to equivalent machine code.
Neither source nor the compilers are required Source program and the interpreter are required
for execution. for execution.

Debugging and testing processes are slow. Debugging and testing processes are fast.
It requires less Execution time. It requires more Execution time.

Assembler

The assembler, like the compiler, is a translator that converts assembly language written program into
machine language program. The resulting program can be executed only when the assembly process is
completed.
An assembler is a program that takes basic computer instructions and converts them into a pattern of
bits that the computer's processor can use to perform its basic operations. Some people call these
instructions assembler language and others use the term assembly language.
Linker (computing)
In computer science, a linker or link editor is a program that takes one or more objects generated by a
compiler and combines them into a single executable program.
In IBM mainframe environments such as OS/360 this program is known as a linkage editor.
On UNIX variants the term loader is often used as a synonym for linker. Other terminology was in use,
too. For example, on SINTRAN III the process performed by a linker (assembling object files into a
Page- 252
Chapter Eleven Programming Language

program) was called loading (as in loading executable code onto a file). [1] Because this usage blurs the
distinction between the compile-time process and the run-time process, this article will use linking for
the former and loading for the latter. However, in some operating systems the same program handles
both the jobs of linking and loading a program; see dynamic linking.

Debugging
The error in a compiler program is termed as bug. A bug in the program can abort a computer run
and/or produce absurd output. The process of location and removal of errors is called debugging. The
errors present in a source program are in general of three types, namely:
(a) Syntax Error (b)Execution Error (c) Logical Error

Syntax Error

These errors occur due to the violation of the rules of the language like incorrect punctuations, invalid
symbolic names, misspelled keywords, illegal statements, etc. These errors get detected at the
compilation stage and are, therefore, also referred to as the compilation errors. The syntax errors are the
easiest to locate and correct since they are identified by error messages indicating the line number in
which they occur and the cause of the error. Execution will begin until all compilation errors have been
eliminated.
Execution Error
Execution errors are detected during execution and may be referred to as the runtime errors. Examples
of the execution errors include:
 Attempts to divide by zero.
 Infinite loops causing no output.
 Taking square root of logarithm of a negative number.
 Sing an array that exceeds the space reserved for it.

It is difficult to locate the specific cause of execution errors in long program or loop.

Logical Error
Logical Errors arise from faulty programming logic as for example, the attempts to execute invalid
sequence of instructions, a valid instruction but with invalid data. These errors are difficult to locate. A
logical program error can be detected by going through the flow chart and by running programs on
some sample data, for which the answer is known.

Program Design
The important techniques which are very useful in designing programs are as follows:

 (a) Modular Program Design


 (b) Structured Program Design
 (c) Top-down and bottom-up Program Design

(a) Modular Program Design


When a program becomes very long and complex, it becomes very difficult for the programmer to
design, test and debug such a program. Therefore, a long and complex program is split into a number of
smaller programs known as modules. A module in itself is a complete program which can be designed,
Page- 253
Chapter Eleven Programming Language

tested and debugged separately. Every module is designed to perform specific task. Some of the
modules may be broken into sub modules, which in turn may contain sub modules of their own and so
on. The technique of writing programs in modules is called modular programming.
The characteristics of a module are:
 A module is designed to perform a single task.
 A module is self-contained and independent of other modules.
 A module has only one entry and one exit point.
 A module can call other module.
The modular design approach has the following advantages over non-module one:
 Program reliability is improved.
 Programmer productivity is increased because it is easier to design code and test the program one
module at a time than all at once.
 The various program modules can be designed and /or coded by different programmer, thus
providing the possibility of earlier compilation.
 In some cases a single module can be used at more than one place in the program. This reduces
the total amount of codes within the program.
 Modules performing common programming tasks can be used in more than one program.
Modular design approach suffers from the following drawbacks:

 Modular programs often need more memory space and extra time.
 It may be difficult task to integrate the various modules written by different programmers into a
single program.
 Testing and debugging of separate modules may prove to be time consuming.
(b) Structured Program Design:
A method of writing program in certain systematic way is known as structured programming. A
structured program is highly readable, easily debugged, easily maintained and can be developed
quickly.

The Structured programming is based on the use of the following techniques:

 Control structure
 Modular Programming, and
 Top-down approach in program design.

(c) Top-down and bottom-up Program Design:


In top-down approach, the program is first considered as a whole and is then sub-divided hierarchically
into fewer complexes, smaller and easily manageable form until a stage is reached when further
breakdown will serve no useful purpose.

The disadvantages of top-down design are that the overall system design may not take good advantages
of the hardware. Bottom-up approach for a program design is just the reserve of the top-down approach.
Lower level sub tasks are designed first and combined/linked to the form a complete program.

Program Documentation

Page- 254
Chapter Eleven Programming Language

Program documentation means writing the explanation about the program in the form of comments and
remarks placed at various places in the program. It indicates what functions are performed by the
program, and how these functions are carried out. It helps the user to understand, maintain and modify
the program. The sentences used in documentation are not executed because the compiler overlooks
them. The documentation included in programs in different common languages are as follows:

(a) FORTRAN: a documentation must be preceded by writing C or * in the first column.


(b) COBOL: An asterisk * in column 7 make a documentation line.
(c) PL/I: A documentation line is enclosed in /* and */ at left and right hand side respectively.
(d) PASCAL: A documentation line is enclosed in a pair of braces {and}.

Programming Tools
A programming tool or software development tool is a program or application that software
developers use to create, debug, maintain, or otherwise support other programs and applications. The
term usually refers to relatively simple programs that can be combined together to accomplish a task,
much as one might use multiple hand tools to fix a physical object.

Categories
Software development tools can be roughly divided into the following categories:
 Performance analysis tools
 Debugging tools
 Static analysis and formal verification tools
 Correctness checking tools
 Memory usage tools
 Application build tools
 Integrated development environments

Library (computing)
In computer science, a library is a collection of resources used to develop software. These may include
pre-written code and subroutines, classes, values or type specifications.
Libraries contain code and data that provide services to independent programs. This allows the sharing
and changing of code and data in a modular fashion. Some executables are both standalone programs
and libraries, but most libraries are not executable. Executables and libraries make references known as
links to each other through the process known as linking, which is typically done by a linker.
As of 2009, most modern software systems provide libraries that implement the majority of system
services. Such libraries have commoditized the services which a modern application requires. As such,
most code used by modern applications is provided in these system libraries.
Data Types
In computer programming, a data type is a classification identifying one of various types of data, such
as floating-point, integer, or Boolean, that determines the possible values for that type; the operations
that can be done on values of that type; and the way values of that type can be stored.
Almost all programming languages explicitly include the notion of data type, though different
languages may use different terminology. Common data types may include:
 Integers,
 Booleans,
 Characters,
Page- 255
Chapter Eleven Programming Language

 Floating-point numbers,
 Alphanumeric strings.
Overview of C Programming Language
Introduction
C is one of the most popular Computer languages today. C was an offspring of the “Basic Combined
Programming Language” called B, developed in the 1960’s at Cambridge University. B language was
modified by Dennis Ritche and was implemented at Bell Laboratory in1972. The new language was
named C. Since it was developed along with the UNIX operating system, it is strongly associated with
UNIX.
Today C is running under a number of operating Systems including MS-DOS. Since MS-DOS is a
dominating operating system for microcomputer, it is natural that C has begun to influence the
microcomputer community at large.

Importance of C
The increasing popularity of C is probably due to its desirable qualities. It is a robust language whose
rich set of built-in-functions and operators can be used to write any complex program. The C compiler
combines the capabilities of an assembly language with the features of high level language and
therefore it is well suited for writing both system software and business packages.
Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators. It is many times faster than BASIC.
There are only 32 keywords and its strength lies in its built in functions. Several standard functions are
available which can be used for developing programs.
C is highly portable. This means that C programs written for one Computer can be run on another with
little or no modification. Portability is important if we plan to use a new computer with a different
operating system.
C language is well suited for structured programming, thus requiring the user to think of a problem in
terms of function modules or blocks. A proper collection of these modules would make a complete
program. This modular structure makes program debugging, testing and maintenance easier.
Another important feature of C is its ability to extend itself. A C program is basically a collection of
functions that are supported by the C library. We can continuously add our own functions to the C
library. With the availability of functions, the programming task becomes simple.

Characteristics of C
We briefly list some of C's characteristics that define the language and also have lead to its popularity
as a programming language. Naturally we will be studying many of these aspects throughout the course.
 Small size
 Extensive use of function calls
 Loose typing -- unlike PASCAL
 Structured language
 Low level (BitWise) programming readily available
 Pointer implementation - extensive use of pointers for memory, array, structures and functions.
C has now become a widely used professional language for various reasons.
 It has high-level constructs.
 It can handle low-level activities.
 It produces efficient programs.
Page- 256
Chapter Eleven Programming Language

 It can be compiled on a variety of computers.


Its main drawback is that it has poor error detection which can make it off putting to the beginner.
However diligence in this matter can pay off handsomely since having learned the rules of C we can
break them. Not many languages allow this. This if done properly and carefully leads to the power of C
programming.
Constants, Variables, and Data Types
A programming language is designed to help processes certain kinds of data consisting of numbers,
characters and strings and to provide useful output known as information. The task of processing of data
is accomplished by executing a sequence of precise instructions called a program. These instructions are
formed using certain symbols and words according to some rigid rules known as syntax (or grammar).
Every program instruction must conform precisely to the syntax rules of the language.
Character Set
The character that can be used to form words, numbers and expressions depend upon the computer on
which the program is run. However a subset of characters is available that can be used on most
personal, micro, and mini and mainframe computers. The Characters in C are grouped into the
following categories:
1. Letters
2. Digits
3. Special Characters
4. White Spaces
Tokens
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a C
program the smallest individual units are known as C Tokens. C has six types of tokens as shown in fig
11.3. C programs are written using these tokens and the syntax of the language.
C Tokens

Keyword (Float,
While)
Identifiers (Main, Constant
amount) (-15.5, 100)

Strings
Operators (+,-, *, / ( “ABC”, YEAR”)
)

Special Symbols
Fig 11.3: Picture of Tokens ( [], {})
Keywords and Identifiers

Page- 257
Chapter Eleven Programming Language

Every C word is classified as either a Keyword or an identifier. All Keywords have fixed meanings and
cannot be changed. Keywords serve as basic building blocks for program statements. The list of all
keywords in ANSI C is listed in Table 11.2. All keywords must write in lowercase. Some compilers
may use additional keywords that must be identified from the C manual.
Table 11.2: ANCI C Keywords
Auto Double int struct
Break Else long switch
Case Enum register typedef
Char Extern return union
Const Float short unsigned
Continue For signed void
Default Goto sizeof volatile
Do If static while
Identifiers refer to the names of variables, functions and arrays. These are user-defined names and
consist of a sequence of letters and digits with a letter as a first character. Both uppercase and lowercase
letters are permitted, although lowercase letters are commonly used. The underscore character is also
permitted in identifiers.
Reserved word
A special word reserved by a programming language or by a program. You are not allowed to use
reserved words as variable names. For example, in BASIC and COBOL, the word IF is reserved
because it has a special meaning.
Reserved words are sometimes called keywords.
Constants
Constants in C refer to fixed values that do not change during the execution of a Program. C supports
several types of Constants.

Constants

Numeric Constants
Single Character String Constant
Constant

Integer Real Constant


Constant
Fig 11.4: Picture of Constant

Libraries
Page- 258
Chapter Eleven Programming Language

Libraries are very important in C because the C language supports only the most basic features that it
needs. C does not even contain I/O functions to read from the keyboard and write to the screen.
Anything that extends beyond the basic language must be written by a programmer. The resulting
chunks of code are often placed in libraries to make them easily reusable. We have seen the standard
I/O, or stdio, library already: Standard libraries exist for standard I/O, math functions, string handling,
time manipulation, and so on. You can use libraries in your own programs to split up your programs
into modules. This makes them easier to understand, test, and debug, and also makes it possible to reuse
code from other programs that you write.

Data Types
C language is rich in data types. Storage representations and machine instructions to handle constants
differ from machine to machine. The variety of data types available allows the programmer to select the
type appropriate to the needs of the application as well as the machine.
ANCI C supports four classes of data types:
1. Primary (or fundamental ) data types.
2. User defined data types.
3. Derived data types
4. Empty data set.
Primary Data Types

Integral Type

Integer Character
Signed type Unsigned type
int Undigned int Signed char
short int unsigned short int Unsigned char
long int unsigned long int

Floating Point Type

floatdoubleLong double

Fig 11.5: Picture of Data Types

Page- 259
Chapter Eleven Programming Language

Data Type Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Float 4 bytes 3.4e-38 to 3.4e+38
Double 8 bytes 1.7e-308to 1.7e+308
Table 11.3: Size and Range of Basic Data Types

Variables
As a programmer, you will frequently want your program to "remember" a value. For example, if your
program requests a value from the user, or if it calculates a value, you will want to remember it
somewhere so you can use it later. The way, your program remembers things is by using variables. For
example:
int b;
This line says, "I want to create a space called b that is able to hold one integer value." A variable has a
name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying
something like:
b = 5;
You can use the value in b by saying something like:
printf("%d", b);
In C, there are several standard types for variables:
 int - integer (whole number) values
 float - floating point values
 char - single character values (such as "m" or "Z")

Rules for varibales:


 First character should be letter or alphabet.
 Keywords are not allowed to use as a variable name.
 White space is not allowed.
 C is case sensitive i.e. UPPER and lower case are significant.
 Only underscore, special symbol is allowed between two characters.
 The length of identifier may be up to 31 characters but only the first 8 characters are
significant by compiler.

Page- 260
Chapter Eleven Programming Language

Escape Sequence Characters (Backslash Character Constants) in C:

Character Constant Meaning


\n New line (Line break)
\b Backspace
\t Horizontal Tab
\f Form feed
\a Alert (alerts a bell)
\r Carriage Return
\v Vertical Tab
\? Question Mark
\' Single Quote
\'' Double Quote
\\ Backslash
\0 Null

Variable Declaration

After designing suitable variable names, we must declare them to the compiler. Declaration does two
things:
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.

Primary Type Declaration

A variable can be used to store a value of any data type. That is, the name has nothing to do with its
type. The syntax for declaring a variable is as follows:
Data-type v1,v2,…..vn;
v1,v2,….vn are the names of variables. Variables are separated by commas. A declaration statement
must end with a semicolon. For example, valid declarations are:

int count;
int number, total;
double ratio;

Page- 261
Chapter Eleven Programming Language

Table 11.4: Data Types and Their Keywords

Data Types Keyword Equivalent


Character char
Unsigned Character Unsigned char
Signed character Signed char
Signed integer Signed int (or int)
Signed short integer Signed short int
Signed long integer Signed long int
Unsigned integer Unsigned int
Unsigned short integer Unsigned short int
Unsigned long integer Unsigned long int
Floating point Float
Double-precision floating Point Double
Extend double precision floating Point Long double

Table 11.5: Storage Classes and Their Meaning

Storage Class Meaning


auto Local variable known to only to the function in which it is declared.
Default is auto.
static Local variable which exists and retains its value even after the control is
transferred to the calling function
extern Global variable known to all functions in the file
register Local variable which is stored in the register

Sample C Program
Sample program 1: printing a message
Consider a very simple program given in fig.11.6, this program when executed, will: produce the
following output:
I see, I remember Main( )
{
/*…….printing begins………*/
Printf(“I see, I remember ”);
/*……..printing ends…………*/
}

Fig.11.6 A program to print one line of text

Page- 262
Chapter Eleven Programming Language

C program needs a main function. (Mandatory)

main( )
{
….


}

Function name
Start of program

Program statements

End of program

Fig.11.7 Format of simple C programs


Sample program 2: Adding Two Numbers
Consider another program which performs addition on two numbers and displays the result. The
complete program is shown in Fig.11.8
/* program ADDITION /* line-1 */
# include<stdio.h> /*line-2 */
main( ) /* line-3 */
{ /* line-4 */
int number1,number2,sum; /* line-5 */
float amount; /* line-6 */
number1 =100; /* line-7 */
number2 =50; /* line-8 */
sum= number1+number2; /* line-9 */
amount = 30.75 + 75.35; /* line-10 */
printf(“%d\n”,sum); /* line-11 */
printf (“%5.2f ”, amount); /* line-12 */
} /* line-13 */

Fig.11.3: Program to add two numbers

Fig11.8: Simple c program for adding two numbers


Basic Structure of C Programs
A function is a subroutine that may include one or more statements designed to perform a specific task.
To write a C program, we first create functions and then put them together. A C program may contain
one or more sections shown in Fig.11.9.

Page- 263
Chapter Eleven Programming Language

Documentation Section
Link Section
Definition Section
Global Declaration

Main( ) Function Section


{
Declaration Part
Executable Part
}
Subprogram Section

Function1
Function2
............
Function n (User-defined functions)

Fig.11.9: An overview of a C program

Execution steps of a ‘C’ Program


Executing a program written in C involves a series of steps. These are:
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from the C library
4. Executing the program

Page- 264
Chapter Eleven Programming Language

System Ready

Program Code Enter Program

Source Program

Edit Source Program

C Compiler Compile Source Program

Yes
Syntax Errors
?

No Object Code

System Library Link with System Library

Executable Object Code

Input Data Execute Object Code

Data Errors
Logic Logic Error
and Data
Errors
?
No Errors

CORRECT OUTPUT Stop


Fig.11.10 Process of compiling and running a C program

Page- 265
Chapter Eleven Programming Language

The Simplest C Program


Let's walk through this program and start to see what the different lines are doing:
#include <stdio.h>
int main()
{
printf("This is output from my first program!\n");
return 0;
}
 This C program starts with #include <stdio.h>. This line includes the "standard I/O library"
into your program. The standard I/O library lets you read input from the keyboard (called
"standard in"), write output to the screen (called "standard out"), process text files stored on the
disk, and so on. It is an extremely useful library. C has a large number of standard libraries like
stdio, including string, time and math libraries. A library is simply a package of code that
someone else has written to make your life easier (we'll discuss libraries a bit later).
 The line int main() declares the main function. Every C program must have a function named
main somewhere in the code. We will learn more about functions shortly. At run time,
program execution starts at the first line of the main function.
 In C, the { and } symbols mark the beginning and end of a block of code. In this case, the block
of code making up the main function contains two lines.
 The printf statement in C allows you to send output to standard out (for us, the screen). The
portion in quotes is called the format string and describes how the data is to be formatted
when printed. The format string can contain string literals such as "This is output from my first
program!," symbols for carriage returns (\n), and operators as placeholders for variables (see
below). If you are using UNIX, you can type man 3 printf to get complete documentation for
the printf function. If not, see the documentation included with your compiler for details about
the printf function.
 The return 0; line causes the function to return an error code of 0 (no error) to the shell that
started execution. More on this capability a bit later.

Steps of making a Program


There are five steps for making a Program by using a Computer:
1. Problem Analysis
2. Program Design
3. Program Coding
4. Program Testing and Debugging
5. Program Maintenance
1. Problem Analysis: In this section after problem fixation data are collected about the problem.
If need chart, graph and list can be used. This is called Problem Analysis. At the time of
problem analysis, we need to focus on the following issues:
 Input Identification and
 Output Identification.
2. Program Design: In order to solve any problem we need to correct the existing system and
design the proposed system. In most cases if we can analysis correctly about a complex system
then we can solve the problem correctly. We can make partitions of a complex problem then it
is easy to solve the total problem. Program design includes the following steps:
 Input Design
Page- 266
Chapter Eleven Programming Language

 Output Design
 Design of Input-Output relationship.
In addition to these steps the following steps needs to be design also:
 Algorithm Design
 Flow Chart Design and
 Preparation of Pseudo code.
3. Program Coding: Program is written by using any suitable programming Language with the
help of algorithm, flow chart and Pseudo code.
4. Program Testing and Debugging: Testing your program is a necessary part of program
creation. Except for trivial programs, testing can never prove that a program is correct. What
testing does is to try to find errors in your code. No matter how many errors you find and fix,
there may be more. Still, tested code is better than untested code.
Debugging is a methodical process of finding and reducing the number of bugs, or defects, in
a computer program or a piece of electronic hardware, thus making it behave as expected.
Debugging tends to be harder when various subsystems are tightly coupled, as changes in one
may cause bugs to emerge in another. Many books have been written about debugging (see
below: Further reading), as it involves numerous aspects, including: interactive debugging,
control flow, integration testing, log files, monitoring (application, system), memory dumps,
profiling, Statistical Process Control, and special design tactics to improve detection while
simplifying changes.
5. Program Maintenance: Due to the situation of external factors we need to change
programs sometimes. This is called Program Maintenance. We need to made documentation of
Program for Program maintenance.

Characteristics of Good Program Design

This is a list of goals that a developer should try and have in their software design. Some goals
contradict other ones, but that is where you have to decide what is best for your program.
1. Minimal Complexity
The main goal in any program should be to minimize complexity.  As a developer most of your time
will be maintaining or upgrading existing code. If it is a complete mess, then your life is going to be
that much harder. Try and avoid those solutions where you use a one line complex solution to replace
20 lines of easy to read code. In a year, when you come back to that code, it will take you that much
longer to figure out what you did.
2. Ease of Maintenance
This is making your code easy to update. Find where your code is most likely going to change, and
make it easy to update. The easier you make it, the easier your life is going to be down the road.   Think
of it as a little insurance for your code.
3. Loose Coupling
So what is loose coupling? It is when one portion of code is not dependant on another to run properly. It
is bundling code into nice little self reliant packages that don’t rely on any outside code.  How do you
do this? Make good use of abstraction and information hiding.
4. Extensibility
This means that you design your program so that you can add or remove elements from your program
without disturbing the underlying structure of the program. A good example would be a plug-in.

Page- 267
Chapter Eleven Programming Language

5. Reusability
Write code that will be able to be used in unrelated projects.  Save yourself some time. Again
information hiding is your best bet for making this happens.
6. High Fan-in
This refers to having a large number of classes that use a given class. This implies that you are making
good use of utility classes. For example you might have a bunch of classes that use the Math class to do
calculations.
7. Low to medium Fan-out
This refers to having a low to medium amount of classes used by any given class.  If you had a class
that includes 7 or more classes this is considered high fan out.  So try and keep the number of classes
you include down to a minimum.  Having a high fan-out suggests that the design may be too complex.
8. Portability
Simply put, design a system that can be moved to another environment.  This isn’t always a requirement
of a program, but it should be considered. It might make your life easier if you find out your program
does have to work on different platforms.
9. Leanness
Leanness means making the design with no extra parts.  Everything that is within the design has to be
there.  This is generally a goal if you have speed and efficiency in mind.  A good example of where this
might come in handy is creating a program that has to run on a system with limited resources (cell
phone, older computers)
10. Standard Techniques
Try and standardize your code.  If each developer puts in their own flavor of code you will end up with
an unwieldy mess. Try to layout common approaches for developers to follow, and it will give your
code a sense of familiarity for all developers working on it.

Operators and Expressions


C support a rich set of operators. C programming language provides several operators to perform
different kind to operations. There are operators for assignment, arithmetic functions, logical functions
and many more. These operators generally work on many types of variables or constants, though some
are restricted to work on certain types. Most operators are binary, meaning they take two operands. A
few are unary and only take one operand.
C operators can be classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume variable A holds
10 and variable B holds 20 then:
Show Examples ↓

Page- 268
Chapter Eleven Programming Language

Following table shows all the arithmetic operators supported by C language. Assume variable A holds
10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
Modulus Operator and remainder of after an integer
% B % A will give 0
division
++ Increment operator increases integer value by one A++ will give 11
-- Decrement operator decreases integer value by one A-- will give 9
Example:
Try following example to understand all the arithmetic operators available in C programming
language:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program it produces following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Page- 269
Chapter Eleven Programming Language

Relational Operators
Following table shows all the relational operators supported by C language. Assume variable A holds
10 and variable B holds 20 then:
Operator Description Example
Checks if the value of two operands is equal or not, if
== (A == B) is not true.
yes then condition becomes true.
Checks if the value of two operands is equal or not, if
!= (A != B) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the
> value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the value
< (A < B) is true.
of right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or
>= equal to the value of right operand, if yes then condition (A >= B) is not true.
becomes true.
Checks if the value of left operand is less than or equal
<= to the value of right operand, if yes then condition (A <= B) is true.
becomes true.

Example
Try following example to understand all the relational operators available in C programming
language:

#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
Page- 270
Chapter Eleven Programming Language

}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program it produces following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Logical Operators:
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0 then:
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0 then:
Operator Description Example
Called Logical AND operator. If both the operands
&& (A && B) is false.
are non zero then condition becomes true.
Called Logical OR Operator. If any of the two
|| (A || B) is true.
operands is non zero then condition becomes true.
Called Logical NOT Operator. Use to reverses the
! logical state of its operand. If a condition is true then !(A && B) is true.
Logical NOT operator will make false.
Example
Try following example to understand all the logical operators available in C programming language:
#include <stdio.h>
main()

Page- 271
Chapter Eleven Programming Language

{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
When you compile and execute the above program it produces following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Assignment Operators:
There are following assignment operators supported by C language:
Page- 272
Chapter Eleven Programming Language

Operator Description Example


Simple assignment operator, Assigns values from right C = A + B will assign value of A +
=
side operands to left side operand B into C
Add AND assignment operator, It adds right operand to
+= C += A is equivalent to C = C + A
the left operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right
-= operand from the left operand and assign the result to C -= A is equivalent to C = C - A
left operand
Multiply AND assignment operator, It multiplies right
*= operand with the left operand and assign the result to left C *= A is equivalent to C = C * A
operand
Divide AND assignment operator, It divides left operand
/= with the right operand and assign the result to left C /= A is equivalent to C = C / A
operand
Modulus AND assignment operator, It takes modulus
%= C %= A is equivalent to C = C % A
using two operands and assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Example
Try following example to understand all the assignment operators available in C programming
language:
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;

Page- 273
Chapter Eleven Programming Language

printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );


c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program it produces following result:
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2

Conditional Operator
The conditional operator is unusual in that it takes three operands. The syntax of this operator is like
this: Condition ? Expression1 : Expression2;
You can think of the conditional operator as if it were a function that works like this:
if ( Condition )
    return Expression1;
else
    return Expression2;
The Condition expression must evaluate to true or false. If it is true Expression1 is evaluated and its
value is returned. If Condition is false Expression2 is evaluated and its value is returned. Both
Expression1 and Expression2 must be the same type (or convertible to the same type).

Bitwise Operators
C's bitwise operators work on the bits stored in integral types. They work similar to the logical
operators except that instead of working on true and false values they work with ones and zeroes. There
are several bitwise operators available:

Symbol Meaning
  ~    Complement
  &    And
  |    Or
  ^    Exclusive-Or

Page- 274
Chapter Eleven Programming Language

  <<   Left shift


  >>   Right shift

Special Operators
C supports some special operators of interest such as comma operator, sizeof operator, pointer
operators(& and *) and member selection operators(. And -). The comma and sizeof operators.There are
a few other operators that are used in C. The [] operator is used to access elements of an array. The
syntax is like this:
int a[5] = { 1, 2, 3, 4, 5 };
int b = a[3];

Operator Description Example


sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.
& Returns the address of an variable. &a; will give actaul address of the variable.
* Pointer to a variable. *a; will pointer to a variable.

Example:
Try following example to understand all the miscellaneous operators available in C programming
language:
#include <stdio.h>
main()
{
int e,a = 4;
short b;
double c;
int* ptr;
printf("Line 1 - Size of variable a = %d\n", sizeof(a) ); /* example of sizeof operator */
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );
ptr = &a; /* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a); /* example of & and * operators */
printf("*ptr is %d.\n", *ptr);
a = 10;
e=5;
b = (a > e) ? (a-e):(a+e); /* example of conditional operator */
printf( "Value of b is %d\n", b );
b = (a < e ) ? (a-e): (a+e);
printf( "Value of b is %d\n", b );
printf( "Value of b is %d\n", b++ ); /* example of increment operator */
printf( "Value of b is %d\n", b );
printf( "Value of b is %d\n",++ b );
printf( "Value of b is %d\n", b-- ); /* example of decrement operator */
printf( "Value of b is %d\n", b );
printf( "Value of b is %d\n",--b );
}
When you compile and execute the above program it produces following result:
Page- 275
Chapter Eleven Programming Language

value of a is 4
*ptr is 4.
Value of b is 5
Value of b is 15
Value of b is 15
Value of b is 16
Value of b is 17
Value of b is 17
Value of b is 16
Value of b is 15
Increment and Decrement Operator
C has two very useful operators not generally found in other languages. These are the increment and
decrement operators:
++ And --
The operator ++ adds 1 to the operand while – subtracts 1.Both are unary operators and take the
following form:
++ m; or m ++; ++m is equivalent to m = m+1; (or m + =1;)

-- m; or m--; --m is equivalent to m = m-1; (or m - = 1;)

** We can find the difference between ++m & m++ and m-- & --m using the following c program

#include <stdlib.h>
#include <stdio.h>
void main()
{
    int x = 5, y=7;
    printf("x=%d\t", ++x);
    printf("x=%d\t", x++);
    printf("x=%d\t", x);
printf("y=%d\t", y--);
    printf("y=%d\t", y);
    printf("y=%d\t", --y);

 }
Output: x=6 x=6 x=7 y=7 y=6 y=5
Arithmetic Expressions
Expressions are evaluated using an assignment statement of the form

Variable = expression;

Page- 276
Chapter Eleven Programming Language

Following are examples of arithmetic expressions :


    result = x - y;
    total = principle + interest;
    numsquare = x * x;
    celcius = (fahrenheit - 32) / 1.8
Notice the equal sign (=) in the above expressions, it is known as the assignment operator. It assigns the
value on the right hand side of the equal sign to the variable on the left hand side.

Decision Making And Branching


A C program is a set of statements which are normally executed sequentially in the order in which they
appear. This happens when no options or no repetitions of certain calculations are necessary. However,
in practice, we have a number of situations where we may have to change the order of execution of
statements based on certain conditions, or repeat a group of statements until certain specified conditions
are met. This involves a kind of decision making to see whether a particular condition has occurred or
not and then direct the computer to execute certain statements accordingly.

C language possesses such decision making capabilities and supports the supports the following
statements known as control or decision making statements.
1. If statement
2. Switch statement
3. Conditional operator statement
4. Goto statement
Decision Making with If Statement
The if statement is a powerful decision making statement and is used to control the flow of execution of
statements. It is basically a two-way decision statement and is used in conjunction with an expression. It
takes the following form:

if (test expression)

It allows the computer to evaluate the expression first and then,


depending on whether the value of the expression (relation or
condition) is ‘true’ (non-zero) or false (zero,) it transfer the control
to a particular statement. This point of program has two paths to
follows, one for the true condition and the other for the false
condition as shown in Fig. 11.11.

Fig11.11: Simple if statement


If statement may be implemented in different forms depending on the complexity of conditions to be
tested.

1. simple if statement
2. if….. else statement
3. Nested if…..else statement

Page- 277
Chapter Eleven Programming Language

4. else if ladder
Simple IF Statement
The general form of a simple if statement is

If (test expression)
{
Statement-block;
}
Statement-x:

The ‘statement-block’ may be a single statement or a group of statements or a group of statements. If


the test expression is true, the statement-block will be executed; otherwise the statement-block will be
skipped and the execution will jump to the statement-x. Remember, when the condition is true both the
statement-block and the statement –x executed in sequence.

Example:
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
if( a < 20 ) /* check the boolean condition using if statement */
{ /* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0; }

When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10

The IF ….ELSE Statement


If…. else statement is an extension of the simple if statement. The general form is

If (test expression)
{

Page- 278
Chapter Eleven Programming Language

True-block statements(s)
}
else
{
False-block statement(s)
}
statement-x

If the test expression is true, then the true-block statement(s), immediately following the if statement are
executed; otherwise, the false-block will be executed, not both. This is illustrated 11.12.In both the
cases, the control is transferred subsequently to statement-x.

Flowchart of if-else Statement:

Example:
#include <stdio.h>
int main ()
{ int a = 100;
if( a < 20 )
{
printf("a is less than 20\n" );
}
else Fig11.12: Flowchart if else statement
{
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0; }

When the above code is compiled and executed, it produces following result:
a is not less than 20; value of a is : 100

Nesting of IF….ELSE Statement


When a series of decisions are involved, we may have to use more than one if…else statement in nested
form as follows:

if (test condition 1)
{
Page- 279
Chapter Eleven Programming Language

if (test condition 2)
{
statement-1;
}
else
{
statement-2
}
}
else
{
statement-3;
}
statement-x;

Fig11.13: Logic execution of nesting of if ........ else statement


The logic of execution is illustrated in Fig.11.13. If the condition-1 is false, the statement-3 will be
executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1
will be evaluated; otherwise the statement-2 will be evaluated and then the control is transferred to the
statement-x.
Example:
#include <stdio.h>
int main ()
{ int a = 100;
int b = 200;
if( a == 100 )
{
if( b == 200 )
{
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;}
When the above code is compiled and executed, it produces following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

The ELSE IF Ladder


There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if. It follows general
form:

Page- 280
Chapter Eleven Programming Language

If (condition 1)
Statement-1;
Else if (condition 2)
Statement-2;
Else if (condition 3)
Statement-3;
………….
Else if (condition n)
Statement-n;
Else
Default- statement;

Statement-x;

Fig11.14: Logic execution of else if ladder Statements

This construct is known as the else if ladder. The conditions are evaluated from the top, downwards. As
soon as a true condition is found, the statement associated with it is executed and the control is
transferred to the statement-x. When all the n conditions become false, then the final else containing the
default-statement will be executed.Fig.11.14 shows the logic of execution of else if ladder Statements.
Example:
#include <stdio.h>
int main ()
{
int a = 100;
if( a == 10 )
{/* if condition is true then print the following */
printf("Value of a is 10\n" );
}
else if( a == 20 )
{ /* if else if condition is true */
printf("Value of a is 20\n" );
}
else if( a == 30 )
{ /* if else if condition is true */
printf("Value of a is 30\n" );
}
else
{/* if none of the conditions is true */
printf("None of the values is matching\n" );

Page- 281
Chapter Eleven Programming Language

}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces following result:
None of the values is matching
Exact value of a is: 100

The SWITCH Statement


We have seen that when one of the many alternatives is to be selected, we can design a program using if
statements to control the selection. However, the complexity of such a program increases dramatically
when the number of alternatives increases. The general form of the switch statement is as shown below:
The expression is an integer expression or characters. Value-1, value-2…. Are constants or constant
expression and are known as case labels. Each of these values should be unique within a switch
statement.block-1, block-2….are statement lists and may contain zero or more statements. There is no
need to put braces around these blocks. Note that case ladies end with a colon (:). When the switch is
executed, the value of the expression is successively compared against the values value-1, value-2,…If
a case is found whose value matches with the value matches with the value of the expression, then the
block of statements that follows the case are executed.

Switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…….
…….
default:
default-block
break;
}
statement-x;

The break statement at the end of each block signals the end of a and causes an particular case and
causes an exit from the statement, transferring the control to the statement-x following the switch. The
default is an optional case. When present, it will be executed if the value of the expression does not
match with any of the case values. If not present, no action takes place if all matches fail and the control
goes to the statement-x.
The selection process of switch statement is illustrated in the flowchart shown in Fig.11.15. The switch
statement can be used to grade the students as discussed in last section. This is illustrated below:

Page- 282
Chapter Eleven Programming Language

Example:
#include <stdio.h>

int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' : Fig11.15 : Flow diagram of switch
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B

Page- 283
Chapter Eleven Programming Language

Decision Making and Looping


In looping, a sequence of statements is executed until some conditions for termination of the loop are
satisfied. A program loop therefore consists of two segments, one known as the body of the loop and
other known as the control statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statements in the loop, a control structure may be classified as
the entry controlled loop or as the exit controlled loop. In the entry controlled loop, the control
conditions are tested before the
start of the loop execution. If the
conditions are not satisfied, then
the body of the loop will not be
executed. In the case of an exit
controlled loop, the test is
performed at the end of the body
of the loop and therefore the
body is executed unconditionally
for the first time. Following
is the general from of a loop
statement in most of the
programming languages:
Fig11.16: Flowchart of loop
C programming language provides following types of loop to handle looping
requirements.
Loop Type Description
Repeats a statement or group of statements while a given condition is
while loop
true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
Like a while statement, except that it tests the condition at the end of the
do...while loop
loop body
You can use one or more loop inside any another while, for or do..while
nested loops
loop.
Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed. C supports the following
control statements.
Control Statement Description
Terminates the loop or switch statement and transfers execution to the
break statement
statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest
continue statement
its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to
goto statement
use goto statement in your program.

Page- 284
Chapter Eleven Programming Language

While loop
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax:
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop
Flow Diagram 11.17:

Here key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 10;

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}

return 0;
}
When the above code is compiled and
executed, it produces following result:
value of a: 10
value of a: 11 Fig11.17: Flowchart of while loop
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Page- 285
Chapter Eleven Programming Language

Do...while loop
Syntax:
The syntax of a do...while loop in C programming language is:
do
{
statement(s);

}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute
again. This process repeats until the given condition becomes false.

Flow Diagram: 11.18

Example:
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

return 0;
}
When the above code is compiled and
executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12 Fig11.18: Flowchart do while loop
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Page- 286
Chapter Eleven Programming Language

For loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.

Flow Diagram: 11.19

Example:
#include <stdio.h>

int main ()
{
/* for loop execution */
for( int a = 10; a < 15; a = a + 1)
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled
and executed, it produces
following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13value of a: 14 Fig11.19: Flowchart of for loop

Page- 287
Chapter Eleven Programming Language

C programming language allows to use one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax:
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );

}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example a for loop can be inside a while loop or vice versa.
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 40:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<40; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0; }

Page- 288
Chapter Eleven Programming Language

When the above code is compiled and executed, it produces following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime

The Infinite Loop:


A loop becomes infinite loop if a condition never becomes false. For loop is traditionally used for this
purpose. Since none of the three expressions that form the for loop are required, you can make an
endless loop by leaving the conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite
loop.

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop
in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.

Break statement
The break statement in C programming language has following two usage:
1. When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops ( ie. one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax for a break statement in C is as follows:

Page- 289
Chapter Eleven Programming Language

Example:
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 10;

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{/* terminate the loop using break
statement*/
break;
}
}
return 0;
}

Fig11.20: Flowchart of break


When the above code is executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

Continue Statement
The continue statement in C programming language works somewhat like the break statement. Instead
of forcing termination, however, continue forces the next iteration of the loop to take place, skipping
any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control passes to
the conditional tests.
Syntax:
The syntax for a continue statement in C is as follows:

Page- 290
Chapter Eleven Programming Language

Example:
#include <stdio.h>

int main ()
{
int a = 10;
do /* do loop execution */
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and
executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14 Fig11.21: Flowchart of continue statement
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Goto statement
A goto statement in C programming language provides an unconditional jump from the goto to a
labeled statement in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax:
The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.

Page- 291
Chapter Eleven Programming Language

Flow Diagram: 11.22

Example:
#include <stdio.h>
int main ()
{
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and
executed, it produces following result: Fig11.22: Flowchart of goto statement
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Arrays and Handling of Character Strings


An array is a group of related data items that share a common name. For instance we can define an
array name salary to represent a set of salaries of a group of employees. A particular value is indicated
by writing a number called index number or subscript in brackets after the array name.

For example,
Salary [10]

Represents the salary of the 10th employee. While the complete set of values is referred to as an array,
the individual values are called elements. Arrays can be of any variable type.

The ability to use a single name to represent a collection of items and to refer to an item by specifying
the item number enables us to develop concise and efficient Programs.

Page- 292
Chapter Eleven Programming Language

One Dimensional Array


A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one dimensional array. In mathematics, we often deal with variables
that are single-subscripted.
The subscripted variable xi can be expressed as x[1], x[2], x[3]…..x[n]
The subscript can begin with number 0. That is x[0].

Declaration of Arrays
The general form of array deceleration is:

Type variable-name [size];


The type specifies the type of element that will be contained in the array, such as int, float or char and
the size indicates the maximum number of elements that can be stored inside the array.
For example, float height [50]; declares the height to be an array containing 50 real elements.
Any subscripts 0 to 49 are valid.

Initialization of Array
We can initialize the elements of array in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is:
Static types array-name [size]={list of values};

The values in the list are separated by commas. For example, the statement Static int
number[3]={0,0,0}

Two Dimensional Arrays


C allows us to define tables of items by using two-dimensional arrays. Two dimensional arrays are
declared as follows:
Type array_name [row_size][column];

Initialization of Two Dimensional array


Two dimensional arrays may be initialized by following their declaration with a list of initial values
enclosed in braces. For example,
Static int table[2][3]={0,0,0,1,1,1};
initializes the elements of the first row to zero and the second row to one. The initialization is
done row by row.

Multidimensional Arrays
C allows array or more dimensions. The exact limit is determined by the compiler. The general form of
a multidimensional array is:
Type array_name[s1][s2]….[sm];

Where si is the size of the ith dimension. Example is: int survey[3][5][12];
Servey is a three-dimensional array decleard to contain 180 integer elements.

Page- 293
Chapter Eleven Programming Language

String
A string is an array of character. Any group of characters defined between double quotation marks is a
constant string.
Example: “Man is obviously made to think”
Character strings are often used to build meaningful and readable programs. The common
operations performed on character strings are:
 Reading and Writing strings
 Combining strings together
 Copying one string to another
 Comparing strings for equality
 Extracting a portion of a string.
A string variable is any valid C variable name and is always declared as an array.
The general form of declaration of a string variable is:
Char string_name [size];
The size determines the number of characters in the string_name. Some examples are:
Char city [10];
Char name [30];

Reading String from Terminal


Reading Words

The familiar input function scanf can be used with %s format specification to read in a string of
character.

Example: char address [15];


scanf (“%s”, address);

Writing String to Screen


We have used extensively the printf function with %s format to print strings to the screen. The format
%s can be used to display an array of characters that is terminated by the null character. For example,
the statement

Printf (“%s”, name); Can be used to display the entire contents of the array name.

String-Handling Functions
Following are the most commonly used string-handling functions:

Functions Action
Strcat() Concatenates two strings
Strcmp() Compares two strings
Strcpy() Copies one string over another
Strlen Finds the length of a string

Page- 294
Chapter Eleven Programming Language

C Program to Find Number of Vowels, Consonants, Digits and White Space


Character

#include<stdio.h>
int main(){
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' ||
line[i]=='I' || line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",s);
return 0;
}

Output:
Enter a line of string:
This program is easy 2 understand
Vowels: 9
Consonants: 18
Digits: 1
White spaces: 5

C Program for strlen()Function

#include <stdio.h>
#include <string.h>
int main(){
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];

Page- 295
Chapter Eleven Programming Language

printf("Enter string: ");


gets(c);
printf("Length of string a=%d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b=%d \n",strlen(b));
printf("Length of string c=%d \n",strlen(c));
return 0;
}
Enter string: String
Length of string a=7
Length of string b=7
Length of string c=6

C Program for strcmp() function


#include <stdio.h>
#include <string.h>
int main(){
char str1[30],str2[30];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
return 0;
}
Enter first string: Apple
Enter second string: Apple
Both strings are equal.

C Program for strcat() function


#include <stdio.h>
#include <string.h>
char str1[27] = "a";
char str2[2];
main()
{
int n;
/* Put a null character at the end of str2[]. */
str2[1] = `\0';
for (n = 98; n< 120; n++)
{
Page- 296
Chapter Eleven Programming Language

str2[0] = n;
strcat(str1, str2);
puts(str1);
}
return(0);
}

Output:
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
abcdefghijk
abcdefghijkl

Function
A function is a group of statements that together perform a task. Every C program has at least one
function which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is so each function performs a specific task.
Each function has a name and it is reusable i.e. it can be executed from as many different parts in a C
Program as required. It also optionally returns a value to the calling program.
So function in a C program has some properties discussed below.
 Every function has a unique name. This name is used to call function from “main ()” function.
A function can be called from within another function.
 A function is independent and it can perform its task without intervention from or interfering
with other parts of the program.
 A function performs a specific task. A task is a distinct job that your program must perform as
a part of its overall operation, such as adding two or more integer, sorting an array into
numerical order, or calculating a cube root etc.
 A function returns a value to the calling program. This is optional and depends upon the task
your function is going to accomplish. Suppose you want to just show few lines through
function then it is not necessary to return a value. But if you are calculating area of rectangle
and wanted to use result somewhere in program then you have to send back (return) value to
the calling function.

Page- 297
Chapter Eleven Programming Language

Types of Function
1. Built in (Library)Function
2. User Define Functions
1. Built in (Library) Function:

The C standard library provides numerous built-in functions that your program can call. For example,
function strcat() to concatenate two strings, function memcpy() to copy one memory location to
another location and many more functions. printf and scanf belongs to the category of library
functions.
Printf: Reading User Values

Here is the simplest printf statement: printf("Hello");


This call to printf has a format string that tells printf to send the word "Hello" to standard out.
The following line shows how to output the value of a variable using printf.
printf("%d", b);
You can also use multiple %d placeholders in one printf statement:
printf("%d + %d = %d\n", a, b, c);

You can print all of the normal C types with printf by using different placeholders:
 int (integer values) uses %d
 float (floating point values) uses %f
 char (single character values) uses %c
 character strings (arrays of characters, discussed later) use %s
Scanf

The scanf function allows you to accept input from standard in, which for us is generally the keyboard.
The simplest application of scanf looks like this:
scanf("%d", &b);
The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is
printf, so b must be declared as an int) and place that value into b.
The scanf function uses the same placeholders as printf:
 int uses %d
 float uses %f
 char uses %c
 character strings (discussed later) use %s
You MUST put & in front of the variable used in scanf.

2.User Define Functions:


A function that is declare, calling and define by the user is called user define function.
A function is known with various names like a method or a sub-routine or a procedure etc. main is an
example of uses defined functions.

Every user define function has three parts as:

Page- 298
Chapter Eleven Programming Language

1. Prototype or Declaration
2. Definition
3. Calling

1. Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:
Return type function_name( parameter list );
For the bellow defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function
in another file. In such case you should declare the function at the top of the file calling the function.

Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}

We May write this as follows


Data-type function-name (type1 a1, type2 a2,….typeN aN)
{
…………….
…………….
Body of the function
…………….
…………….
}

Here data-type refers to the type of the value returned by the function function-name and type1,
type2………typeN are types of arguments a1, a2…..aN.
As usual, if no data type is specified for the function then, by default, the function is assumed to return
an integer value. The argument declaration is done using the comma separator.
For Example, double funct (int a, int b, double c)

A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:

Page- 299
Chapter Eleven Programming Language

 Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a value.
In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
 Parameter List: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function. Parameters
are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what the
function does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

3.Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a function, you
will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when its return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.
To call a function you simply need to pass the required parameters along with function name and if
function returns a value then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
Page- 300
Chapter Eleven Programming Language

printf( "Max value is : %d\n", ret );


return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and complied the source code. While running final
executable, it would produce following result:
Max value is : 200

Example of a simple function to add two integers

#include<stdio.h>
#include<conio.h>
Function Declaration add(int x,int y)
void main()
{
clrscr();
add(10,15);
Function calling add(55,64);
add(168,325);
getch();
}
void add(int x,int y)
{
User define function int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}

Output of the program: Sum of 10 and 15 is 25


Sum of 55 and 64 is 119
Sum of 168 and 325 is 493

Page- 301
Chapter Eleven Programming Language

Types of Function calls

Functions are called by their names. If the function is without argument, it can be called directly using
its name. But for functions with arguments, we have two ways to call them,

Call Type Description


This method copies the actual value of an argument into the formal
1.Call by value parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
2.Call by reference
argument used in the call. This means that changes made to the
parameter affect the argument.
By default, C uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function and above mentioned example while calling max()
function used the same method.
Call by value Example:
The call by value method of passing arguments to a function copies the actual value of an argument
into the formal parameter of the function. In this case, changes made to the parameter inside the
function have no effect on the argument.
By default, C programming language uses call by value method to pass arguments. In general, this
means that code within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Now let us call the function swap() by passing actual values as in the following example:
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */

Page- 302
Chapter Eleven Programming Language

swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put above code in a single C file, compile and execute it, it will produce following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Call by reference Example

The call by reference method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument used in
the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}

For now, let us call the function swap() by passing values by reference as in the following example:
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
Page- 303
Chapter Eleven Programming Language

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );
return 0;
}
Let us put above code in a single C file, compile and execute it, it will produce following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Advantages of using functions


There are many advantages in using functions in a program they are:
1. It makes possible top down modular programming. In this style of programming, the high level
logic of the overall problem is solved first while the details of each lower level functions is
addressed later.
2. The length of the source program can be reduced by using functions at appropriate places.
3. It becomes uncomplicated to locate and separate a faulty function for further study.
4. A function may be used later by many other programs this means that a c programmer can use
function written by others, instead of starting over from scratch.
5. A function can be used to keep away from rewriting the same block of codes which we are
going use two or more locations in a program. This is especially useful if the code involved is
long or complicated.

Category of Functions
A function, depending on whether arguments are presents or not and whether a value is returned or not,
may belong to one of the following categories. There are five types of functions and they are:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return values.

A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable can not be accessed. There are three places where variables can be
declared in C programming language:
1. Inside a function or a block which is called local variables,
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.
Let us explain what are local and global variables and formal parameters.

Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to functions
outside their own. Following is the example using local variables. Here all the variables a, b and c are
local to main() function.

Page- 304
Chapter Eleven Programming Language

#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

Global Variables
Global variables are defined outside of a function, usually on top of the program. The global variables
will hold their value throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables:
#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but value of local variable inside a
function will take preference. Following is an example:
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main ()
{ /* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}

Page- 305
Chapter Eleven Programming Language

When the above code is compiled and executed, it produces following result:
value of g = 10

Formal Parameters
A function parameters, formal parameters, are treated as local variables with-in that function and they
will take preference over the global variables. Following is an example:
#include <stdio.h>

/* global variable declaration */


int a = 20;

int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;

printf ("value of a in main() = %d\n", a);


c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces following result:
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

C-Array
C programming language provides a data structure called the array, which can store a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

Page- 306
Chapter Eleven Programming Language

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10-element array called balance of
type double, use this statement:
double balance[10];
Now balance is avariable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ]. Following is an example to assign a single element of the
array. If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will
be 5th ie. last element because all arrays have 0 as the index of their first element which is also called
base index. Following is the pictorial representation of the same array we discussed above:

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
Page- 307
Chapter Eleven Programming Language

int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 8; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107

C Arrays in Detail
Arrays are important to C and should need lots of more detail. There are following few
important concepts related to array which should be clear to a C programmer:
Concept Description
C supports multidimensional arrays. The simplest form of the
Multi-dimensional arrays
multidimensional array is the two-dimensional array.
You can pass to the function a pointer to an array by specifying the
Passing arrays to functions
array's name without an index.
Return array from a function C allows a function to return an array.
You can generate a pointer to the first element of an array by simply
Pointer to an array
specifying the array name, without any index.
Multi-dimensional arrays Example:

C programming language allows multidimensional arrays. Here is the general form of a


multidimensional array declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];

Page- 308
Chapter Eleven Programming Language

Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array
is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y
you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two
dimensional array can be think as a table which will have x number of rows and y number of columns.
A 2-dimentional array a which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays


Multidimensionalarrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts ie. row index and column
index of the array. For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram. Let us check below program where we have used nested loop to handle a two dimensional
array:

#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

Page- 309
Chapter Eleven Programming Language

int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
When the above code is compiled and executed, it produces following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most
of the arrays you create will be of one or two dimensions.

Passing arrays to functions Example


If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received. Similar
way you can pass multi-dimensional array as formal parameters.
Way-1
Formal parameters as a pointer as follows. You will study what is pointer in next chapter.
void myFunction(int *param)
{
.
}
Way-2
Formal parameters as a sized array as follows:

void myFunction(int param[10])


{
.
}

Page- 310
Chapter Eleven Programming Language

Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
.
}
Example
Now consider the following function which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed through the
array as follows:
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}

Now let us call the above function as follows:


#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{ /* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
When the above code is compiled together and executed, it produces following result:
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for the formal parameters.

Page- 311
Chapter Eleven Programming Language

Return array from a function Example:


C programming language does not allow to return an entire array as an argument to a function.
However, You can return a pointer to an array by specifying the array's name without an index. You
will study pointer in next chapter so you can skip this chapter until you understand the concept of
Pointers in C.
If you want to return a single-dimension array from a function, you would have to declare a
function returning a pointer as in the following example:
int * myFunction()
{
.
}
Second point to remember is that C does not advocate to return the address of a local variable to outside
of the function so you would have to define the local variable as static variable.
Now consider the following function which will generate 10 random numbers and return them
using an array and call this function as follows:
#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( )
{
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}

/* main function to call above defined function */


int main ()
{ /* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
When the above code is compiled together and executed, it produces result something as follows:
r[0] = 313959809
r[1] = 1759055877

Page- 312
Chapter Eleven Programming Language

r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
*(p + 9) : 1990469526

Pointer
Pointers are used everywhere in C, so if you want to use the C language fully you have to have a very
good understanding of pointers. They have to become comfortable for you. The goal of this section and
the next several that follow is to help you build a complete understanding of pointers and how C uses
them. For most people it takes a little time and some practice to become fully comfortable with pointers,
but once you master them you are a full-fledged C programmer.
C uses pointers in three different ways:
 C uses pointers to create dynamic data structures -- data structures built up from blocks of
memory allocated from the heap at run-time.
 C uses pointers to handle variable parameters passed to functions.
 Pointers in C provide an alternative way to access information stored in arrays. Pointer
techniques are especially valuable when you work with strings. There is an intimate link
between arrays and pointers in C.
In some cases, C programmers also use pointers because they make the code slightly more efficient.
What you will find is that, once you are completely comfortable with pointers, you tend to use them all
the time.

Pointer Basis
To understand pointers, it helps to compare them to normal variables.
A "normal variable" is a location in memory that can hold a value. For example, when you declare a
variable i as an integer, four bytes of memory are set aside for it. In your program, you refer to that
location in memory by the name i. At the machine level that location has a memory address. The four
bytes at that address are known to you, the programmer, as i, and the four bytes can hold one integer
value.
A pointer is different. A pointer is a variable that points to another variable. This means that a pointer
holds the memory address of another variable. Put another way, the pointer does not hold a value in the

Page- 313
Chapter Eleven Programming Language

traditional sense; instead, it holds the address of another variable. A pointer "points to" that other
variable by holding a copy of its address.
Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the
address. That addresses points to a value. There is the pointer and the value pointed to. This fact can be
a little confusing until you get comfortable with it, but once you get comfortable it becomes extremely
powerful.
The following example code shows a typical pointer:
#include <stdio.h>
int main()
{
int i,j;
int *p; /* a pointer to an integer */
p = &i;
*p=5;
j=i;
printf("%d %d %d\n", i, j, *p);
return 0;
}
The first declaration in this program declares two normal integer variables named i and j. The line int
*p declares a pointer named p. This line asks the compiler to declare a variable p that is a pointer to an
integer. The * indicates that a pointer is being declared rather than a normal variable. You can create a
pointer to anything: a float, a structure, a char, and so on. Just use a * to indicate that you want a pointer
rather than a normal variable.
The line p = &i; will definitely be new to you. In C, & is called the
address operator. The expression &i means, "The memory address of
the variable i." Thus, the expression p = &i; means, "Assign to p the
address of i." Once you execute this statement, p "points to" i. Before
you do so, p contains a random, unknown address, and its use will
likely cause a segmentation fault or similar program crash.
One good way to visualize what is happening is to draw a picture. After
i, j and p are declared, the world looks like this:

In this drawing the three variables i, j and p have been declared,


but none of the three has been initialized. The two integer
variables are therefore drawn as boxes containing question
marks -- they could contain any value at this point in the
program's execution. The pointer is drawn as a circle to

distinguish it from a normal variable that


holds a value, and the random arrows
indicate that it can be pointing anywhere at
this moment.

Page- 314
Chapter Eleven Programming Language

After the line p = &I;, p is initialized and it points to i, like this:

Once p points to i, the memory location i has two names. It is still known as i, but now it is known as
*p as well. This is how C talks about the two parts of a pointer variable: p is the location holding the
address, while *p is the location pointed to by that address. Therefore *p=5 means that the location
pointed to by p should be set to 5, like this:

Because the location *p is also i, i also takes on the value 5. Consequently, j=i; sets j to 5, and the
printf statement produces 5 5 5.
The main feature of a pointer is its two-part nature. The pointer itself holds an address. The pointer also
points to a value of a specific type - the value at the address the point holds. The pointer itself, in this
case, is p. The value pointed to is *p.

Using Pointers for Function Parameters


Most C programmers first use pointers to implement something called variable parameters in
functions. You have actually been using variable parameters in the scanf function -- that's why you've
had to use the & (the address operator) on variables used with scanf. Now that you understand pointers
you can see what has really been going on.
To understand how variable parameters work, lets see how we might go about implementing a swap
function in C. To implement a swap function, what you would like to do is pass in two variables and
have the function swap their values. Here's one attempt at an implementation -- enter and execute the
following code and see what happens:

#include <stdio.h>
void swap(int i, int j)
{
int t;
t=i;
i=j;
j=t;
}
void main()
{
int a,b;
a=5;
b=10;
printf("%d %d\n", a, b);
swap(a,b);
printf("%d %d\n", a, b);
}
When you execute this program, you will find that no swapping takes place. The values of a and b are
passed to swap, and the swap function does swap them, but when the function returns nothing happens.
To make this function work correctly you can use pointers, as shown below:

Page- 315
Chapter Eleven Programming Language

#include <stdio.h>
void swap(int *i, int *j)
{
int t;
t = *i;
*i = *j;
*j = t;
}
void main()
{
int a,b;
a=5;
b=10;
printf("%d %d\n",a,b);
swap(&a,&b);
printf("%d %d\n",a,b);
}
To get an idea of what this code does, print it out, draw the two integers
a and b, and enter 5 and 10 in them. Now draw the two pointers i and j,
along with the integer t. When swap is called, it is passed the
addresses of a and b. Thus, i points to a (draw an arrow from i to a)
and j points to b (draw another arrow from b to j). Once the pointers
are initialized by the function call, *i is another name for a, and *j is
another name for b. Now run the code in swap. When the code uses *i
and *j, it really means a and b. When the function completes, a and b
have been swapped.

Suppose you accidentally forget the & when the swap function is
called, and that the swap line accidentally looks like this: swap(a, b);. This causes a segmentation fault.
When you leave out the &, the value of a is passed instead of its address. Therefore, i points to an
invalid location in memory and the system crashes when *i is used.
This is also why scanf crashes if you forget the & on variables passed to it. The scanf function is using
pointers to put the value it reads back into the variable you have passed. Without the &, scanf is passed
a bad address and crashes.

Structure
C arrays allow you to define type of variables that can hold several data items of the same kind but
structure is another user defined data type available in C programming, which allows you to combine
data items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book:
Title
Author
Book ID

Page- 316
Chapter Eleven Programming Language

Need of structure
We have seen that an array can hold a number of values or elements, but all must be of the same type. A
structure is a collection of simple variables but the variables may be of different types. Some can be
int; some can be float and so on.

Defining a Structure
To define a structure, you use struct keyword. Here is the common syntax of structure definition:
struct struct_name{ structure_member };

Declaring structure
To create or declare a structure instance, you can do it in two ways:
The first way is to declare a structure followed by structure definition like this :
1 struct struct_name {
2       structure_member;
3       ...
4     } instance_1,instance_2 instance_n;
In the second way, you can declare the structure instance at a different location in your
source code after structure definition. Here is structure declaration syntax :
1 struct struct_name instance_1,instance_2 instance_n;
At the end of the structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional. Here is the way you would declare the Book structure:
struct Books
{
char title[50];
char author[50];
int book_id;
} book;

Complex structure
If a structure contains arrays or other structures, it is called complex structure. For example address
structure is a structure. We can define a complex structure called customer which contains address
structure as follows:
1 struct customer{
2       char name[50];
3       structure address billing_addr;
4       structure address shipping_addr;
5     };

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we

Page- 317
Chapter Eleven Programming Language

wish to access. You would use struct keyword to define variables of structure type. Following is the
example to explain usage of structure:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 and Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Md. Ali Hossain");
Book1.book_id = 20131;
/* book 2 specification */
strcpy( Book2.title, " The Essentials of Computer Science");
strcpy( Book2.author, " Uzzal Kumar Prodhan");
Book2.book_id = 20132;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces following result:
Book 1 title : C Programming
Book 1 author : Md Ali Hossain
Book 1 book_id : 20131
Book 2 title : The Essentials of Computer Science
Book 2 author : Uzzal Kumar Prodhan
Book 2 book_id : 20132

Copy a structure into another structure


One of major advantage of structure is you can copy it with = operator. The syntax as
follows
1 struct_intance1 = struct_intance2
be noted that some old C compilers may not supports structure assignment so you have to assign each
member variables one by one.

Page- 318
Chapter Eleven Programming Language

Dynamic initialization of structure variables


At the time of declaring the variable of the structure we can assign values.
Our next program will create two structure variables and the value of the members of the first variable
will be assigned to the members of the second variable.

#include< stdio.h >


struct part
{
 int model, partno;
 float cost;
 };
 void main ()
 {
  struct part part1={10,20,30.25};
  struct part part2;
  clrscr ();
  printf ("Model (1st):-%d", part1.model);
  printf ("\nPart number (1st) :-%d", part1.partno);
  printf ("\nCost of the part (1st) Rs.:-%.2f", part1.cost);
  part2=part1;
  printf ("\nModel (2nd):-%d", part2.model);
  printf ("\nPart number (2nd) :-%d", part2.partno);
  printf ("\nCost of the part (2nd) Rs.:-%.2f", part2.cost);
  getch ();
}

Structures as Function Arguments


You can pass a structure as a function argument in very similar way as you pass any other variable or
pointer. You would access structure variables in the similar way as you have accessed in the above
example:

#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( )
{
struct Books Book1; /* Declare Book1 and Book2 of type Book */
strcpy( Book1.title, "C Programming");
Page- 319
Chapter Eleven Programming Language

strcpy( Book1.author, "Md. Ali Hossain");


Book1.book_id = 20131;
/* book 2 specification */
strcpy( Book2.title, " The Essentials of Computer Science");
strcpy( Book2.author, " Uzzal Kumar Prodhan");
Book2.book_id = 20132;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces following result:
Book 1 title : C Programming
Book 1 author : Md Ali Hossain
Book 1 book_id : 20131
Book 2 title : The Essentials of Computer Science
Book 2 author : Uzzal Kumar Prodhan
Book 2 book_id : 20132

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other variable as
follows:
struct Books *struct_pointer;
Now you can store the address of a structure variable in the above defined pointer variable. To find the
address of a structure variable, place the & operator before the structure's name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the -> operator as
follows:
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you to understand the
concept:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
int book_id;
};

Page- 320
Chapter Eleven Programming Language

void printBook( struct Books *book );


int main( )
{
struct Books Book1; /* Declare Book1 and Book2 of type Book */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Md. Ali Hossain");
Book1.book_id = 20131;
strcpy( Book2.title, " The Essentials of Computer Science");
strcpy( Book2.author, " Uzzal Kumar Prodhan");
Book2.book_id = 20132;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces following result:
Book 1 title : C Programming
Book 1 author : Md Ali Hossain
Book 1 book_id : 20131
Book 2 title : The Essentials of Computer Science
Book 2 author : Uzzal Kumar Prodhan
Book 2 book_id : 20132

Union
A union is a special data type available in C that enables you to store different data types in the same
memory location.You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for multi-
purpose.
Defining a Union
To define a union, you must use the union statement in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your program.
The format of the union statement is
as follows:
union union_name
{
member definition;
member definition;
...
member definition;
Page- 321
Chapter Eleven Programming Language

} [one or more union variables];


The union _name is the name of union and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the
final semicolon, you can specify one or more union variables but it is optional. Here is the way you
would define a union type named Data which has the three members i, f, and str:
union Data
{
int i;
float f;
char str[20];
} data;
Now a variable of Data type can store an integer, a floating-point number, or a string of characters. This
means that a single variable ie. same memory location can be used to store multiple types of data. You
can use any built-in or user defined data types inside a union based on your requirement. The memory
occupied by a union will be large enough to hold the largest member of the union. For example, in
above example Data type will occupy 20 bytes of memory space because this is the maximum space
which can be occupied by character string. Following is the example which will display total memory
size occupied by the above union:

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces following result:
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access operator
is coded as a period between the union variable name and the union member that we wish to access.
You would use union keyword to define variables of union type. Following is the example to explain
usage of union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;

Page- 322
Chapter Eleven Programming Language

float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces following result:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here we can see that values of i and f members of union got corrupted because final value assigned to
the variable has occupied the memory location and this is the reason that the value if str member is
getting printed very well. Now let's look into the same example once again where we will use one
variable at a time which is the main purpose of having union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( “data.i : %d\n”, data.i);
data.f = 220.5;
printf( “data.f : %f\n”, data.f);
strcpy( data.str, “C Programming”);
printf( “data.str : %s\n”, data.str);
return 0;
}
When the above code is compiled and executed, it produces following result:
data.i : 10
data.f : 220.500000
data.str : C Programming
Here all the members are getting printed very well because one member is being used at a time.

Page- 323
Chapter Eleven Programming Language

Difference between Structure & Union


Structure Union
i. Access Members     
We can access all the members of structure at
Only one member of union can be accessed at anytime.
anytime.
ii. Memory Allocation     
Allocates memory for variable which variable require
Memory is allocated for all variables.
more memory.
iii. Initialization     
All members of structure can be initialized Only the first member of a union can be initialized.
iv. Keyword     
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
v. Syntax     
struct struct_name union union_name
{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;
vi. Example     
struct item_mst union item_mst
{ {
int rno; int rno;
char nm[50]; char nm[50];
}it; }it;

File Management
It is necessary to have a more flexible approach where data can be stored on the disk and read whenever
necessary, without destroying the data. This method employs the concept of files to store data. A file is
a place on the disk where a group of related data is stored. Like most other languages, C supports a
number of functions that have the ability to perform basic file operations, which include:

1. naming a file
2. opening a file
3. reading data from a file
4. writing data to a file and
5. Closing a file.

Page- 324
Chapter Eleven Programming Language

Table 11.7: High level I/O functions

Function Name Operation


fopen() Creates a new file for use
Opens an existing file for use
flose() Closes a file which has been opened for use.
getc() Reads a character from a file.
putc() Writes a character to a file.
fprintf() Writes a set of data values to a file.
fscanf() Reads a set of data values from a file.

getw() Reads an integer from a file


putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file.
ftell() Gives the current position in the file
rewind() Sets the positions to the beginning of the file.

Defining and Opening a File


If we to store data in a file in the secondary memory, we must specify certain things about the file, to
the operating system. They include:
1. File name
2. Data Structure
3. Purpose.
File name is a string of characters that make up of a valid filename for the operating system. It may
contain two parts, a primary name and an optional period with the extension. For example:
Input.data
Store
Prog.c
Data structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore, all files should be declared as type FILE before they are used. FILE is a defined data type.
When we open a file, we must specify what we want to do with the file. For example, we may write
data to the file or read the already existing data.
Following is the general format for declaring and opening a file:

FILE *fp;
Fp = fopen (“filename”, “mode”);

The first statement declares the variable fp as a “pointer to the data type FILE”. As stated earlier, FILE
is a structure that is defined in the I/O library. The second statement opens the file named filename and
assigns an identifier to the FILE type pointer fp.This pointer which contains all the information about
the file is subsequently used as a communication link between the system and the program.
Page- 325
Chapter Eleven Programming Language

The second statement also specifies the purpose of opening this file. The mode does this job.
Mode can be one of the following:

r open the file for reading only.


w open the file for writing only.
a open the file for appending (or adding) data to it.

When trying to open a file, one of the following things may happen:

1. When the mode is ‘writing`, a file with the specified name is created if the file does not
exist. The contents are deleted, if the file already exists.
2. When the purpose is ‘appending`, the file is opened with the current contents safe. A file
with the specified name is created if the file does not exist.
3. If the purpose is ‘reading`, and if it exists, then the file is opened with the current contents
safe; otherwise an error occurs.
Consider the following statements:
FILE *p1, *p2;
p1 = fopen (“data”, “r”);
p2 = fopen (“results”, “w”);
The file data is opened for reading and results is opened for writing. In case, the results file already
exists, its contents are deleted and the file is opened as a new file. If data file does not exist, an error
will occur.
Many recent compilers include additional modes of operation. They include:

r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
We can open and use a number of files at a time. This number however depends on the system we use.

<<CLOSING A FILE >>


It takes the following form:

fclose(file_pointer);

This would close the file associated with the FILE pointer file_pointer . Look at the following segment
of a program.
……………
……………
FILE *p1, * p2 ;
p1 = fopen(“INPUT”, “w”);
p2 = fopen(“OUTPUT”, “r”);
…………….
…………….
fclose(p1);

Page- 326
Chapter Eleven Programming Language

fcolse(p2);

This program opens two files and closes them after all operations on them are completed. Once a file is
closed, its file pointer can be reused for another file.

The getc and putc Functions


The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar functions
and handle one character at a time. Assume that a file is opened with mode w and file pointer fp1. Then
, the statement
putc (c, fp1);

writes the character contained in the character variable c to the associated with FILE pointer
fp1.Similarly, getc is used to read a character from a file that has been opened in read mode. For
example, the statement
c = getc (fp2); would read a character from the file whose file pointer is fp2.
The getw and putw Functions
The getw and putw are integer-oriented functions. They are similar to the getc and putc functions and
are used to read and write integer values. These functions would be useful when we deal with only
integer data. The general forms of getw and putw are:

getw(fp) putw(integer, fp);

The fprintf and fscanf Function


The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf and scanf
functions, except of course that they work on files. The first argument of these functions is a file pointer
which specifies the file to be used. The general form of fprintf is
fprintf (fp, “control string”, list);
where fp is a file pointer associated with a file that has been opened for writing. The control string
contains output specifications for the items in the list. The list may include variables, constants and
strings.

A C program contains the following statements.


#include <stdio.h>
#define NULL 0
main( )
{
FILE * f p t ;
fpt = fopen("sample.dat", " r + " ) ;
if ( fpt == NULL)
printf("\nERROR - Cannot open the designated f i l e \ n " ) ;
else {
fclose ( f p t ) ;
Page- 327
Chapter Eleven Programming Language

}
}
This program attempts to open an existing data file called sample. dat for both reading and writing. An
error message will be generated if this data file cannot be found. Otherwise the data file will be opened
and processed, as indicated.
The fopen and the i f statments are often combined, as follows.
if( ( fpt = fopen(“sample.datn”,"r+"))== NULL)
printf("\nERROR - Cannot open the designated f i l e \ n " ) ;
Either method is acceptable.
/ * read a l i n e of lowercase t e x t and store i n uppercase w i t h i n a data f i l e * /
#include <stdio.h>
#include <ctype.h>
main( )
{
FILE * f p t ; / * define a pointer t o predefined structure type FILE */
char c;
/ * open a new data f i l e f o r w r i t i n g only */
f p t = fopen("sample.dat", "w");
/ * read each character and w r i t e i t s uppercase equivalent t o the data f i l e */
do
putc(toupper(c = getchar()), f p t ) ;
while (c I = ' \ n o ) ;
/ * close t h e data f i l e */
fclose ( f p t ) ;
}
After the program has been executed, the data file sample. dat will contain an uppercase equivalent of
the line of text entered into the computer from the keyboard. For example, if the original line of text
had been

We, the people of the Bangladesh

the data file would contain the text

WE, THE PEOPLE OF THE Bangladesh

C program for fscanf() and fprint()


#include <stdio.h>
main ()
{
  FILE *fp;
  float total;
  fp = fopen("data.txt", "w+");
  if (fp == NULL) {
    printf("data.txt does not exist, please check!\n");
    exit (1);
  }

Page- 328
Chapter Eleven Programming Language

  fprintf(fp, 100);
  fscanf(fp, "%f", &total);
  fclose(fp);
  printf("Value of total is %f\n", total);
}

The output: Value of total is 100

ftell()
Functions ftell() and fseek() are important in a program performing file manipulations. Function ftell()
returns the current position of the file pointer in a stream. The return value is 0 or a positive integer
indicating the byte offset from the beginning of an open file. A return value of -1 indicates an error.
Prototype of this function is as shown below:

      long int ftell(FILE *fp);

fseek()
This function positions the next I/O operation on an open stream to a new position relative to the
current position.

       int fseek(FILE *fp, long int offset, int origin);

Here fp is the file pointer of the stream on which I/O operations are carried on, offset is the number of
bytes to skip over. The offset can be either positive or negative, denting forward or backward movement
in the file. origin is the position in the stream to which the offset is applied, this can be one of the
following constants :

    SEEK_SET : offset is relative to beginning of the file


    SEEK_CUR : offset is relative to the current position in the file
    SEEK_END : offset is relative to end of the file

#include <stdio.h>
#include <stdlib.h>
char buffer[11];
int position;
main ()
{
  FILE *file_ptr;
  int num;
  if ((file_ptr = fopen("test_file", "w+f 10"))
== NULL)
  {
   printf("Error opening test_file \n");
   exit(1);
Page- 329
Chapter Eleven Programming Language

  }
  fputs("1111111111", file_ptr);
  fputs("2222222222", file_ptr);
  if ( (position = fseek(file_ptr, 10, SEEK_SET)) != 0)
  {
   printf("Error in seek operation: errno \n");
   exit(1);
  }
  num = 11;
  fgets(buffer, num, file_ptr);
  printf("The record is %s\n", buffer);
  fclose(file_ptr);
}

The output:      The record is 2222222222.

Note: Here the fopen() function accepts "w+f 10" as the mode. This indicates that a fixed file is created
if it does not exist or opened if it exists and the file's record size is 10.

Program to writes numbers in a file and read and find odd or even numbers from
it in C Programming

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA file\n\n");
f1 = fopen("DATA","w"); /* create a data file */
for(i=1;i<=20;i++)
{
scanf("%d",&number);
if(number==-1)break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA","r");
f2 = fopen("ODD","w");
f3 = fopen("EVEN","w");
while((number = getw(f1)) != EOF) /* Read from Data file */
{
if(number%2==0)
putw(number,f3);
Page- 330
Chapter Eleven Programming Language

else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen("ODD","r");
f3 = fopen("EVEN","r");
printf("\n\nContents of ODD file \n\n");
while((number = getw(f2)) != EOF)
printf("%4d",number);
printf("\n\nContents of EVEN file \n\n");
while((number = getw(f3)) != EOF)
printf("%4d",number);
fclose(f2);
fclose(f3);
getch();
}

Output:

Contents of ODD file 1 3 5 7 9 11 13 15 17 19

Contents of EVEN file 2 4 6 8 10 12 14 16 18 20

Page- 331
Chapter Eleven Programming Language

Exercise

1: What do you mean by Program and Programming Language?


2: Describe about Machine Language, Assembly Language and High Level Language.
3: Describe the importance of C and the characteristics of C programming language.
4: Describe Constants, Variables, and Data Types
5: Describe about Translator: (Compiler, Interpreter, Assembler)
6: Write the differences between Compiler and Interpreter
7: Briefly Describe about Debugging.
8: Briefly Describe about Program Design.
9: Briefly describe about Program Documentation
10: Describe the basic structure of C Program.
11: What are the characteristics of good program design?
12: Describe different Operators
13: Describe Simple IF, IF ….ELSE, Nesting of IF….ELSE and ELSE IF Ladder statement with
flowchart.
14: Describe SWITCH and GOTO Statement with flowchart.
15: Describe While, Do, for and Do-while loop.
16: What is Functions? Describe standard library and User-Defined function.
17: What are the Scope and Lifetime of Declarations?
18: Describe Pointer with example.
19: What is Structure? What are the needs of structure?
20: What do you mean file management?

Page- 332

You might also like