Chapter Eleven
Chapter Eleven
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.
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
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.
Page- 250
Chapter Eleven Programming Language
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
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.
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:
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.
Control structure
Modular Programming, and
Top-down approach in program design.
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:
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
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
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
floatdoubleLong double
Page- 259
Chapter Eleven Programming Language
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")
Page- 260
Chapter Eleven Programming Language
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.
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
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…………*/
}
Page- 262
Chapter Eleven Programming Language
main( )
{
….
…
…
}
Function name
Start of program
Program statements
End of program
Page- 263
Chapter Eleven Programming Language
Documentation Section
Link Section
Definition Section
Global Declaration
Function1
Function2
............
Function n (User-defined functions)
Page- 264
Chapter Eleven Programming Language
System Ready
Source Program
Yes
Syntax Errors
?
No Object Code
Data Errors
Logic Logic Error
and Data
Errors
?
No Errors
Page- 265
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.
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.
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
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
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
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];
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;)
** 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
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)
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:
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
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.
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
if (test condition 1)
{
Page- 279
Chapter Eleven Programming Language
if (test condition 2)
{
statement-1;
}
else
{
statement-2
}
}
else
{
statement-3;
}
statement-x;
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;
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
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
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;
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.
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.
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
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;
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
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
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
Declaration of Arrays
The general form of array deceleration is:
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}
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];
The familiar input function scanf can be used with %s format specification to read in a string of
character.
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
#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
#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
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
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.
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
}
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
#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);
}
Page- 301
Chapter Eleven Programming Language
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,
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
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
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>
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
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:
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:
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.
#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;
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;
}
Page- 311
Chapter Eleven Programming Language
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:
Page- 314
Chapter Eleven Programming Language
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.
#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 };
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
Page- 318
Chapter Eleven Programming Language
#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
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
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
#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
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
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
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:
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.
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.
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:
}
}
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
Page- 328
Chapter Eleven Programming Language
fprintf(fp, 100);
fscanf(fp, "%f", &total);
fclose(fp);
printf("Value of total is %f\n", total);
}
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:
fseek()
This function positions the next I/O operation on an open stream to a new position relative to the
current position.
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 :
#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);
}
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:
Page- 331
Chapter Eleven Programming Language
Exercise
Page- 332