0 ratings0% found this document useful (0 votes) 2K views45 pagesAdvanced C Programming by A P Godse
best book to learn c programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
aieia tel el arate)
Advanced C Programming
Technical Publications Pune’‘Table of Contents :
Chapter-1 Basin Elements nf C (1. t)to (1 - 30)
}Chapter-2 Operators and Expressions 2+ t)to (2 24)
Chapier-3 Input and Output Statements (3-1) t0 (3-24
Chapter-4 Decision Making, Branching & Looping 4 - 1) to (4-38)
Chapter-5 —_Arrays and Strings 5 - 1) 0 (5 - 38)
Chapter-6 Pointers (6 - t}to (6-32)
Chapter-7 Functions (-1)6(7-24)
Chapter-6 Storage Classes 8 - 1)0 (B+ 12)
Chanter -9 User Defined Data Types (9 - 1) to (9 - 28)
Chapter-10 File Handling (10-4) to (10-38)
Ghapter+11 Advanced Features 111) to (11 + 30)
Appendix -A Programming Examples (A= 1)t04A- 62)
Best of Technical Publications
As per Revised Syllabus of Anna University (Coimbatore) - 2007 Course:
Semester-IH [CSE/I.T.] %
k= Advanced C Programming
S Computer Architecture
? Digital Principles and Systems Design
Principles of Communication
(4)Advanced C Programming
ISBN 9788184314960
Al rights reserved with Technicol Publications. No part of this book should be
reproduced in any form, Electronic, Mechanical, Photocopy or any information storage and
relrievel system without prior permission in writing, fram Tachaicel Publications, Pune.
Published by
Technical Publications Pune”
#1, Anit Residency, 412, Shaniwar Peth, Pune - 411 030, Inks
Printer :
K Joshi & Co.
1945/9, Sadhashv Peth,
Pine - 411030,nis less than 0. Have your program print an error message if n <0, then go back and
read in the next pair of numbers of without computing the sum, Are any values of x
also illegal ? If So, test for them too. . . . . AA 54
Program 49 . Write a C program to find the roots of a quadratic equation. . A=55
Program 50 . Write aC program to reverse the first n characters in a file.
(Note : The fle name and n are specified on the command line.)........... A-56
Program 51 . Write a C program to convert a Roman numeral to its decimal equivalent. ... A-57
Program 52. Write a'C program that displays the position or index in the string S where the string
T begins, or - 1 if S does not contain T.........
Program 53 . Write a C program that uses function to insert a sub-string into given main string from
agiven position, . A-59
Program 54. 2's complement of a number is obtained by scanning it from shtto to left and
complementing all the bits after the first appearance of a 1. Thus 2's complement
of. of 400 és 00100. Write a C program to find the 2's conrleent otabioayBasic Elements of C
C is a computer programming language. This means, we can use C to create lists
of instructions for a computer to follow. C is one of thousands of programming
languages currently in use. C has been around for several decades and has won
widespread acceptance because it gives programmers maximum control and efficiency.
C is an easy language to learn. It is a bit more cryptic in its style than some other
languages, but we get beyond that fairly quickly.
1.1 History of C
The C language is developed by Dennis Ritchie at AT&T Bell Laboratories, in 1972.
It was named C because many of its features were derived from an earlier language
called B. In 1970, the Ken Thompson developed and named language as B since it was
a stripped down version of the BCPL (Basic Combined Programming Language).
BCPL was developed by Martin Richards, in 1967.
Most of the modern languages including ANSI/ISO C are derived from the
ALGOL, introduced in the 1960s. It was the first language to use block structure.
ALGOL never gained wide acceptance in the United States, but it was widely used in
Europe.
After introduction of ‘Traditional C’ language by Dennis Ritchie in 1972, it was
confined to use within Bell Laboratories until 1978, when Brian Kernighan and Ritchie
published a book 'The C Programming Language’. The book was so popular that the
language at that time is commonly referred to as "K&R C’. By the mid 1980s, the
popularity of C has become wide spread. Numerous C compilers and interpreters had
been written for computers. of all sizes, and many commercial application programs
had been developed. Early commercial implementations of C differed somewhat from
Kernighan and Ritchie's original definition, resulting in minor incomy
between different implementations of the language. To avoid incompatil
problems for system developers due to them, in 1983, the American National
Standards Institute formed a committee to produce a C programming language
standard. This “ANSI C” was completed in 1988, and was approved in 1989, It was
then approved by the International Standards Organization (ISO) in 1990. The Fig. 1.
shows the history of ANSI C.
(@-4)Advanced C Programming 4-2 Basic Elements of C
Developed by International Group in 1960
Developed by Martin Richards in 1967
Developed by Ken Thompson in 1970
Developed by Dennis Ritchie in 1972
Developed by Kernighan and Ritchie in 1978
Developed by ANSI committee in 1989
ANSgstandards
Approved by ISO committee in 1990
Fig. 1.1 History of ANSI C
1.2 Characteristics of C
We briefly list some of the characteristics of C language that define the language.
The characteristics give an idea why C has now become a widely used professional
language.
Program written in C has comparatively small size.
It allows loose typing — unlike PASCAL.
It is a structured language.
It is a complied language, i.e. once we write C program, we have to run it
through a C compiler to turn program into an executable. C compilers are
commonly available.
It supports pointer implementation - extensive use of pointers for memory,
array, structures and functions.
It has only 32 keywords.
It provides large number of built-in functions. It recommends extensive use of
function calls.
It has high-level constructs,Advanced C Programming 1-3 Basic Elements of C
© It can handle low-level activities. Low level (Bitwise) programming readily
available.
It produces efficient and fast running programs.
© It can be compiled on a variety of computers.
* It is highly portable. This means that programs written on one computer can
run on another computer having different operating system with little or no
modification.
1.3 Simple C Programs
The only way to learn a new programming language is by writing programs in it,
ie. learning by examples. The first program in C to display a message “hello students”
is as follows.
Though the program is very simple, the important points in the program are as
follows :
© The first line in the program is comment that identifies the purpose of the
program. The comment begins with /* and ends with */
* include allows the program to interact with the screen, keyboard
and file system of our computer. #include is a preprocessor directive. It
includes the information required to execute specific functions from the
specified header file. (in this program stdio.h) in the program when it is
complied. The blank space between # and include is not permitted.
© Every C program contains a function called main. This is the start point of the
program. main() declares the start of the function, while the two curly brackets
show the start and finish of the function. Curly brackets in C are used to
group statements together as in a function, or in the body of a loop. Such a
grouping is known as a compound statement or a block.
naterialAdvanced C Programming 1-4 Basic Elements of C
* printf(“hello, students\n”); This is a statement in the program. The printf is a
built-in function provided by C. It prints the words on the screen. The text to
be printed is enclosed in double quotes. The \n at the end of the text tells the
program to print on the next line of the output.
+ It is important to note that each statement within the compound statement
ends with a semicolon.
Most C programs are in lower case letters. We will usually find upper case
letters used in preprocessor definitions (which will be discussed later) or
inside quotes as parts of character strings. C is case sensitive, that is, it
recognizes a lower case letter and it’s upper case equivalent different.
In the above program few new things are introduced which are as follows:
© The words, number and sq are variable names. They are used to store numeric
data. Here, both numbers are declared as integer data type. The word int is a
keyword for integer.
© scanf("%d", &number); This is a statement in the program. The scanf is a
built-in function provided by C. It reads the value of the variable and assigns
the value to the specified variable.
+ The argument %d in the scanf/printf functions tells compiler that the value of
the number should be read/printed as a decimal integer.
Copyrighted materialAdvanced C Programming 1-5 Basic Elements of C
© The ampersand symbol (&) before variable name number is an operator that
specifies the variable name's address.
© sq = number * number; This is a particular type of expression statement called
an assignment statement. This statement causes the square to be calculated
from the given value of number. Within the statement the asterisks (*)
represents multiplication sign.
* The output section shows the program output. The bold matter shown is
entered by the user.
In the above program few new things are introduced which are as follows:
The comments at the end of each line have been added in order to emphasize
overall program organization.
© fidefine statement is preprocessor compiler directive. It assigns a constant
value to the symbolic name (PI in this program).
© The words radius and area are variable names. They are used to store numeric
data. Here, both numbers are declared as floating point data type. The word
float is a keyword for floating point.
The argument %f in the scanf/printf functions tells compiler that the value of
the radius/area should be read/printed as a floating point number.Advanced C Programming Basic Elements of C
The above program uses user defined function to change the value of variable
num, Let us talk few things about function. The detail description of function is given
in chapter 7.
* A function is a self contained program segment that carries out some specific,
well-defined task. Here, function modifies the value of variable num.
+ Every C program consists of one or more functions (in this program two
functions). One of these functions must be a main function.
* Execution of the program will always begin by carrying out the instructions in
main.
+ The program has one argument in the function that is declared as integer. The
value of num is passed on to n when the function modify ( ) is called.
+ The function returns the modified value to the main ( ) function when it is
called in the statement.
num = modify (num) ;
Copyrighted materialAdvanced C Programming Basic Elements of C
1.4 Structure of C Program
The programs given in the previous sections give the brief idea of a structure of C
program. C program can be viewed as a group of building blocks called funetions.
The function is subroutine program which includes one or more statements to perform
specific task. The Fig. 1.2 shows the structure of the C program.
Fig. 1.2 Structure of C program
Copyrighted materialAdvanced C Programming 1-8 Basic Elements of ©
‘As shown in the Fig. 1.2, every C program should consist of :
Document Section (Optional)
The C program begins with a document section. It includes a set of comment lines
giving information such as name of the program, purpose of the program and other
details. The documentation part is not compulsory; however it is recommended.
Written by : AP. Godse
Date : 1/8/2008
Preprocessor Directives
+ The preprocessor directives or precompiler directives are the special
instructions to the preprocessor that tell it how to prepare our program for
compilation. It begins with a number symbol (#) as a first non-blank character.
One of the most’ important preprocessor directive is include. The include
directive is used to tell the preprocessor that we need information from the
selected library file known as header file.
* The #define is also the commonly used preprocessor directive. It assigns a
constant value to the symbolic constants.
#include
#include
#include
#define Name value
#define PI 3.14159
#define MAX 100Advanced C Programming 1-9 Basic Elements of C
Global Declaration Section
By declaring the variables outside of all the functions, they can be made
accessible to all functions in the program. Such variables are known as global
variables and they are declared in’ the global declaration section which is
outside of all the functions.
The declaration of user defined function is also included in the global
declaration section.
Main Function Section
The program may contain one or more functions, one of which must be
main () function.
The program will always begin by executing the main function.
Additional function definitions in the program may precede or follow main ( ).
The program execution begins at the opening curly brace and ends at the
closing curly brace of the main function.
Main Function Section Example
Syntax : main()
{
function body |
) |
Example: main()
{
int number, sq; 7* Declayations */
print{(‘Number = #* Executable statement */
scanf("%d", &number); #* Executable statement */
sq = number * number; /* Executable statement */
printf(‘\nSquare = %d", sq); /* Executable statement */
}
The main function body (the portion of the program within the opening and
closing curly braces) has two parts ; declarations and executable statements.
The declarations declare all the variables except global variables used in the
executable statements of the function. The variables declared within the
function can be accessed only in that function. Such variables are known as
local variables.Advanced C Programming 1-10 Basic Elements of C
User Defined Function Section
User Defined Function Section Example
|
|
|
Syntax : for function without input arguments :
ftype function_name()
{
function body
}
| Example: — int cubo()
{
int number, c; /* Declarations */
printf(‘Number = /° Executable statement */
scanf("%d", &number); /* Executable statement */ |
G = number * number * number; —_/* Executable statement */
return(c}; /* Executable statement */
}
Syntax : for function with input arguments
ftype function_name(argument list)
{
function body
+
i :
Example; — int cube(int number)
{
int c; #* Declarations */
c= number* number * number; —_/* Executable statement */
return(c); /* Executable statement */
}
Each user function must contain ;
+ A function heading, which consists of a function name followed by an
optional list of arguments enclosed in parenthesis. In the above example, int
keyword preceding function name indicates that the function will return
integer value.Advanced C Programming 4-11 Basic Elements of C
© A list of argument declarations, if arguments are included in the heading
(Arguments are symbols that represent information being passed betiveen the
functions and other parts of the program).
+ Function body, it is similar to m,
also contains declaration:
function body, i.e. user-defined function
and executable statements.
Important Notes :
* All declarations and executable statements should be ended with semicolon.
* Except main function all other parts are optional in the program. They are
included as per the requirements of the program.
1.5 Program Style
Most of the programs are examined or studied by someone other than the original
programmer. In industry, programmers spend considerably more time on program
maintenance (that is, updating and modifying the program) than they do on its
original design or coding. Keeping these things in mind, the program that is neatly
stated and whose meaning is clear makes everyone's job simpler. Let us see the
important tips to make program neat and clear.
/* This program adds two integer numbers written by : A. P Godse */
#inelude< stdio.h > Ncrereancel
main()
{ and readable names Prove sorimer
int num_i = 15, num_2 = 20; /* Local declaration */
int sum;
sum = num_1 + num 2; /* calculate and assign the sum */
printf ( ‘Sum of two numbers is = %a", sum );)/* print the sum */
———— Use of
renee identation
‘opening and
closing braces
Fig. 1.3 Program style example
* Write all program sections in lowercase letters except symbolic constants and
text message enclosed in the double quotes (" ”) in the printf statement.
* Braces group program statements together and mark the beginning and end of
functions, Beginning and end braces must be aligned.
* Give proper indentation of brace and statement to make program easier to
read and debug.Advanced C Programming 1-12 Basic Elements of C
«Insert proper comments to easily understand program logic. They are very
iiseful for debugging and testing, the program. Excessive comments should be
avoided because they may decrease program readability.
* Choose meaningful names for variables and user defined functions, so their
use is easy to understand. If a name consists of two or more words, placi
the underscore character (_) between words will improve the readability of the
name. For example, rupees_per_hour instead of rupees perhour.
* Choose name long enough to convey proper meaning. But avoid excessively
long names because they may increase the chances of typing errors.
+ To avoid confusion, do nat choose names that are similar to each other.
1.6 Editing, Compiling and Executing the Program
Developing a program in a compiled language such as C requires at least four
steps:
+ editing (or writing) the program
* compiling it
linking it and
+ executing it
The Fig. 14 illustrates the process of editing, compiling, linking, and executing C
program.
1.6.1 Editing
Once the program has been handwritten, it must be entered into the computer
before it can be complied, linked and executed. We need editor for this purpose. The
editor program allows us to type the program directly inte a window on the screen
and save the resulting text as a separate file. This is often referred to as the source file
(we can read it with the TYPE command in DOs or the eat command in UNTX). The
important thing is that the text of a C program is stored in a file with the extension .c
for C programming language.
To enter a new program in turbo C++ editor, we have to simply type the program
into the editing area on a line-by-line basis and press the enter key at the end of each
line. To edit the program in the line, we have to use the mouse or the cursor
movement (arrow) keys to locate the beginning of the edit area. Then we have to use
backspace or Delete keys to remove unwanted characters. We may also insert
additional characters, as required. We may delete one or more lines by selecting
(highlighting) the lines and then selecting Cut from the Edit Menu, or pressing Delete
key. The Cut and Paste selections in the Edit menu allows movement of block of lines
from one location to other.Advanced C Programming 1-13 Basic Elements of C
Fig. 1.4 Flowchart showing sequence of editing, compiling, linking, and
executing G programAdvanced C Programming 1-14 Basic Elements of C
Once the program has been entered, it should be saved before it is executed. In
Turbo C++, this is accomplished by selecting Save As from the File menu, and
supplying a program name, such as HELLO.C. Once the program has been saved, it
can again be saved after recent changes at some later time simply by selecting Save
from the File menu.
The program that has been saved can later be recalled by selecting Open from the
File menu, and then either typing the program name or selecting the program name
from a list of stored programs.Advanced C Programming 1-15 Basic Elements of C
1.6.2 Compiling
We cannot directly execute the source file. Therefore, once the program has been
entered into the computer, edited and saved, it can be compiled by selecting Compile
from the Compile menu. A new window will then be opened which gives the
information about warnings and errors in the program if any. If the program does not
compile successfully, a list of error messages will appear in a separate message
window. A successful compilation produces an intermediate object file - with the
extension .ob}, the .ob3 stands for Object. We can also compile the program file by
using short-cut keys - AILE9,
~ Ei +
finclude
main()
€
printf ("Hello world");
?
apie tl the active Edit window. r a
Fig. 1.5 (c) Turbo C++ Editor with Compile Menu
1.6.3 Linking
The first question that comes to most people's minds is why is linking necessary?
The main reason is that many compiled languages come with library routines which
can be added to the program. These routines are written by the manufacturer of the
compiler to perform a variety of tasks, from input/output to complicated
mathematical functions. In the case of C the standard input and output functions are
contained in a library (stdio.h) so even the most basic program will require a library
function.
The object file can be linked by selecting Link from the Compile menu. A new
window will then be opened which gives the information about warnings and errors
in the program if any. A successful linking produces an executable file - with the
extension .exe, the .exe stands for Executable.
It is important to note that Build All from the Compile menu does the
compilation of the program and if compilation is error free, it does linking of theAdvanced C Programming 1-16 Basic Elements of C
program immediately after the compilation. If compilation results error, the object file
is not created and hence there is no question of linking.
1.6.4 Executable Files
The text editor produces .c source files, which go to the compiler, which produces
-obj object files, which go to the linker, which produces .exe executable file. We can
then run .exe files as we run other applications, simply by typing their names at the
DOs prompt or run from the Run menu. We can also run the executable file by using
short-cut keys - Ctrl+F9.
1.6.5 Using Microsoft C
© Edit stage: Type program using one of the Microsoft Windows. editing
packages.
+ Compile and link ; Select Building from Make menu. Building option allows
us to both compile and link in the same option,
+ Execute : Use the Run menu and select Go option.
Errors : First error highlighted. Use Next Error from Search menu for further
errors if applicable.
1.6.6 Unix Systems
In Unix operating system, the program is entered using a text editor ed or vi. The
program file name should have extension .c. It is important to note that Unix is a case
sensitive operating system and files named firstprog.c and FIRSTPROG.c are
treated as two separate files on this system. The command for calling the editor and
creating the program file is
ed filename
If file already exists, it is loaded; otherwise a new file with the given name is
created.
By default the Unix system compiles and links a program in one step, as follows:
ce firstprog.c
This command creates an executable file called a.out that overwrites any existing
file called a.out. Executable files on Unix are run by typing their name. In this case
the program is run as follows:
aout
If we want to prevent overwriting of previously created a.out file, we have to
rename it before creating another one. This is accomplished by using the command
ce -0 name source_fileAdvanced C Programming 1-17 Basic Elements of C
For example : cc -o firstprog firstprog.c
This produces an executable file called £irstprog which runs as follows:
firstprog
1.7 The Character Set of C
C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9,
and certain special characters as building blocks to form a basic C program elements
such as constants, variables, operators, expressions, etc. The Table 1.1 shows the entire
character set of C.
Uppercase Letters | ABCDEFGHIJKLMNOPQRSTUVWXYZ
Lowercase Letters | abcdetfghijkimnopqrstuvwxyz
Digits 0123456788
Special Characters | , comma & ampersand period * caret
semicolon colon 2 question mark | ' apostrophe
* quotation mark | ! exclamation | vertical bar I slash
mark
\ backstash = tide under score | $ dollar sign
% percent sign | * asterisk = minus sign + plus sign
< opening angle
bracket (or less
than sign)
> dosing angle
bracket (or
greater than sign)
J right bracket
Horizontal Tab
Table 1.1 The character set of C
(lef parenthesis |) right
parenthesis
[left bracket
{left brace
} right brace
# number sign
Blank space carriage retum
Trigraph Characters
A trigraph is a sequence of three characters that begins with two question marks
(22). We use trigraphs to write C source files with a character set that does not
contain convenient graphic representations for some punctuation characters. They
provide the way to enter certain characters that are not available on some keyboard.
(The resultant C source file is not necessarily more readable, but it is unambiguous.)
The list of all defined trigraphs is shown in Table 1.2.Advanced C Programming 1-18 Basic Elements of C
Trigraphs | Character(s) Description
Represented
22 # pound sign or number sign
2% U left bracket
2) 1 right bracket
Ne { left brace
D> } right brace
2 \ backslash
27 A caret
7 | pipe or vertical bar
2 = tide
Table 1.2 Trigraph characters
The translator replaces each trigraph with its equivalent single character
representation, Thus we can always treat a trigraph as a single source character. The
translator does not alter any other sequence that begins with two question marks.
For example, the expression statements:
printf(*Case ??=3 is done??/n);
print£("You said what??2?/n”);
are equivalent to:
printf ase #3 is done\n");
printf(*You said what2?\n");
1.8 C Tokens
C language programs are composed of lexical elements. The lexical elements of the
C language are characters and white spaces that are grouped together into tokens.
Kinds of tokens in C are :
= Identifiers
* Keywords
+ Constants
* Operators
In this section we study identifiers, keywords and constants. Operators are
discussed in the next chapter,Advanced C Programming 1-19 Basic Elements of C
1.8.1 Identifiers
“Identifiers” or “symbols” are the names we give for variables, types, functions,
and labels in our program. Identifier names must differ in spelling and case from any
keywords. We cannot use keywords as identifiers; they are reserved for special use.
We can create an identifier by specifying it in the declaration of a variable, type, or
function.
Identifiers
[
| © Consist of only sequence of letters, digits, and the special character
| underscore (_).
|
+ We cannot use keywords as identifiers.
* A letter or underscore must be the 1 character of an identifier.
* Cis case-sensitive: Apple and apple are two different identifiers.
* C€ recognizes. only the first 31 characters. Additional characters are
carried along for programmer convenience.
Valid variable names
var.1
num'2
this
fumt 426East
a_long_identitior +more
Table 1.3 Examples of valid and invalid identifiers
1.8.2 Keywords
In C there are certain reserve characters, called keywords. They have standard,
predefined meanings, Keywords can be used only for their intended purpose; they
cannot be used as programmer-defined identifier. We cannot use keywerds as
identifiers; if we do, the compiler reports an error. The Table 14 shows the list of
standard keywords.Advanced ¢ Programming Basic Elements of C
const
continue
defautt
do
Table 1.4 ANSI C keywords
1.8.3 Constants
Constants provide a way to define a variable which cannot be modified during the
execution of the program, Constants can be defined by placing the keyword const in
front of any variable declaration. There are four basic types of constants in C. These
are:
© integer constants : 0, 37, 2001
* floating constants : 0.8, 199.33, 1.0
* character constants : ‘a’, ‘5’, ‘+"
© string constants ; “2”, "vonday”
Integer and floating point constants represent numbers and hence they are often
referred to as numeric constants.
1.8.3.1 Integer Constants
An integer constant is an integer-valued number. It can represent decimal, octal, or
hexadecimal values.
Decimal Constant
A decimal constant contains any of the digits 0 through 9, preceded by an optional
- or + sign. The first digit cannot be 0, Integer constants beginning with the digit 0 are
interpreted as an octal constant, rather than as a decimal constant. In decimal
constants embedded spaces, commas, and non-digital characters are not permitted
between digits. The Table 1.5 shows the valid and invalid decimal constants with
reason for invalidity.Advanced C Programming 1-21 Basic Elements of C
Valid Decimal Constants Invalid Decimal Constants
485976 13,43Sillegal character comma (,).
— 433132211 10.234lllegal character period (.).
+20 10 456illegal character biank scape ( ).
5 65-976lllegal character dash (-).
956 054367 The first digit cannot be zero.
Table 1.5 Decimal constants
Hexadecimal Constants.
A hexadecimal constant begins with the 0 digit followed by either an x or X,
followed by any combination of the digits 0 through 9 and the letters a through f or A
through F. The letters A (or a) through F (or f) represent the values 10 through 15,
respectively. Table 1.6 shows the examples of hexadecimal constants.
Valid Hexadecimal Gonstants| —_ Invalid Hexadecimal Gonstants
0x 12,4lllegal character (.)
0 A436Does not begin with Ox or OX
0x7 Baillegal character (.)
OxAG3illlegal character (G)
Table 1.6 Hexadecimal constant
Octal Constants
An octal constant begins with the digit 0 and contains any of the digits 0 through
7,
Valid Octal Constants Invatid Octal Constants
24315Does not begin with zero
O4681Iliogal digit 8
07,34ltiegal character (.)
05,45illagal character (.)
Table 1.7 Octal constant
The magnitude of integer constant can range from zero to some maximum value
that varies from one compiler to another compiler. If 16-bits are allotted to store
integer constant, the maximum value is 2'°-1, ic. 32767 decimal (equivalent to 77777
octal or 7FFF hexadecimal). If 32-bits are allotted to store integer constant, the
maximum value is 2"'-1, i.e. 2,147,483,647 decimal.Advanced C Programming 1-22 Basic Elements of C
Unsigned and Long Integer Constants
Unsigned integer constants can have only positive values hence they may exceed
the magnitude of ordinary integer constants by approximately factor of 2. An
unsigned integer constant can be identified by appending the letter U (either
uppercase or lower case) to the end of the constant.
Long integer constants may exceed the magnitude of ordinary integer constants,
but requires more number of bits, ic. memory in the computer. Long integer constant
can be identified by appending the letter L (either uppercase or lower case) to the end
of the constant. The Table 1.8 shows the examples of unsigned and long integer
constants.
Constant Number system
4sese67U Decimal (unsigned)
95643. Decimal (Long)
68S46UL Decimal (unsigned Long)
045366. Octal (Long)
satu
oxAsb0L
oxescr4u Hexadecimal (unsigned)
Table 1.8 Unsigned and long integers
1.8.3.2 Floating-Point Constants
Floating-point constants are numbers with decimal parts. A floating-point constant
consists of:
¢ An integral part
* A decimal point
* A fractional part
* An exponent part
+ An optional suffix.
integer Fractional
part part
Optional
ESS
Decimal Exponent
point part
Fig. 1.6 Floating point constantAdvanced C Programming 1-23 Basic Elements of C
Both the integral and fractional parts are made up of decimal digits. The number
either contains a decimal point or an exponent or both. We can omit either the integral
part or the fractional part, but not both. We can omit either the decimal point or the
exponent part, but not both.
+ A suffix of f or F indicates a type of float, and a suffix of I or L indicates a
type of long double. If a suffix is not specified, the floating-point constant has
a type double.
* A plus (+) or minus (-) symbol can precede a floating-point constant.
However, it is not part of the constant; it is interpreted as a unary operator.
* The limits for floating-point values are set in the float.h include file.
The Table 1.9 shows the examples of vatid floating-point constants.
Value
53876
4e-11 9.00000000004 double
1e+5, 1100000 double
7.3216-3 0.007321 double
3.264 32000
0.S0-6f 0.000008
0.45
60000000000 tong double
Table 1.9 Examples of valid floating-point constants
The Table 1.10 shows the examples of invalid floating-point constants with reason
for invalidity.
Invalid Floating-Point Reason for Invalidity
Constants
23 Either decimal point or an expanent must be present.
3,500.0 Megal character (,)
4E+10.3 Exponent must be an integer quantity; it cannot contain a decimal point.
SE 10 Wega! character blank space in the exponent.
Table 1.10 Examples of invalid floating-point constants
If a floating-point constant is too large in magnitude in C, it is set to the largest
value representable by the type. If it is too small in magnitude, it is set to zero.
1.8.3.3 Character Constants
A character constant is a single character, enclosed within the pair of single
quotation mark (apostrophes). The examples of character constants are :
‘Any 6 >” “esAdvanced C Programming 1-24 Basic Elements of C
a
© A character constant is enclosed in single quotes.
See
© Any number enclosed in single quotes is a character constant; however, it is
not same as number. For example, character constant '6' is not same as
number 6.
© The last character constant in the above examples is blank space, which
is typed by pressing the apostrophe key, the space bar and the
apostrophe key.
Backslash Character Constants (Escape Sequences)
In addition to the character, there can be backslash (\) between the two quote
marks. The backslash (\) is known as eseape character. A backslash followed by one
or more special character is known as escape sequence. The escape sequences are
used to express certain non-printing characters, as well as the backslash and the
apostrophe. The Table 1.11 shows the escape sequences used in C.
Escape Sequence Character Represented
‘NO Null character
‘\at Alert (bell, alarm)
"\bt Backspace
"er Form feed (new page)
"nt New-line
"Net Carriage return
"ct Horizontal tab
"wv" Vertical tab
ne Single quotation mark
ne Double quotation mark
"2" Question mark
™t Backslash_
‘\oo0" Octal number
‘\xhh' Hexadecimal number
Table 1.11 Escape sequences used in C
Note : The null character constant ‘\0' is not equivalent to character constant ‘0’.Advanced C Programming 1-25 Basic Elements of C
1.8.3.4 String Constants
A string constant or literal contains a sequence of zero or more characters or
escape sequences enclosed in double quotation marks. For example ,
7* the empty string */
"al 7* string with one character */
“Hello students’ /* string with more than one character */
The quotes are not part of the string, but serve only to delimit it. The same escape
sequences used in character constants apply in strings; \" represents the double-quote
character. String constants can be concatenated at compile time: “hello, ” “students” is
equivalent to “hello, students”. This is useful for splitting up long strings across
several source lines.
« A string constant or literal contains a sequence of zero or more characters
‘or escape sequences enclosed in double quotation marks.
* A string constant is an array of characters.
* The internal representation of a string has a null character ‘\0’ at the end,
so the physical storage required is one more than the number of characters
written between the quotes.
* There is no limit to how long a string can be, but programs must scan a
string completely to determine its length. The standard library function
strlen(s) retums the length of the string in characters.
1.8.4 Basic Data Types and Sizes
C supports several data types, cach of which may be represented differently
within the computer's memory. The basic data types in C are int, char, float and
double. In addition, there are a number of qualifiers that can be applied to these basic
types. The qualifiers short, long, signed and unsigned apply to integer whereas long
apply to double. The following tables show the data types with necessary description.Advanced C Programming 41-26 Basic Elements of C
Data type Description Required Memory | Min Value Max Value
int Represent integers : signed — = 32,768, 3276T
unsigned 0 65,535
int Represent integers : signed 4 Bytes — 2,147,483,648 | 2,147,483,647
unsigned 0 4,294 967,295
short int | Represent integers : signed 2 Bytes — 32,768 32767
unsigned ° 65,535,
tong int | Represent intogers : signed aioe ~ 2,147,983,648 | 2,147,483,647
unsigned Bee 0 - | 4,294967.295
* Some computers use 48, 64 or more bits
Description Required Memory| Min. Value | Max. Value
char signed single character 1 Bytes - 128 127
char unsigned single character 1 Bytes 0 255
Required Memory Min Value Max Value
4 Bytes 34e-38 3.4e+38
double 8 Bytes 1.7e-308 1.7e+308,
long double 10 Bytes 3.4e~4992 ide+4932
1.8.5 Variables
‘A variable is an identifier that is used to represent specified type of information. It
is a name associated with a memory location(s) that have a type, such as integer,
character or float and consequently a size, which is inherited from their type. The
values stored in the variables can change as the program executes, thus we can assign
different data values at various places within the program. However, the data type
associated with the variable cannot change.
Every variable has a name and a value. The name identifies the variable, the value
stores data. There is a limitation on what these names can be. Every variable name inAdvanced C Programming 1-27 Basic Elements of C
C must start with a letter, the rest of the name can consist of letters, numbers and
underscore characters, C recognises upper and lower case characters as being different
so x and X are two different names. Finally, we cannot use any of C’s keywords like
main, while, switch ete. as variable names. Examples of legal variable names include :
Examples of Variable Names.
x | resut outfile | _bestyet
xt [2 out file best_yet
Pern ama nico
It is conventional to avoid the use of capital letters in variable names. These are
used for names of symbolic constants. At least the first 31 characters of an internal
name are significant. For function names and external variables, the number may be
less than 31, because external names may be used by assemblers and loaders over
which the language has no control, For external names, the standard guarantees
uniqueness only for 6 characters and a single case.
An array is another type of variable. It is also an identifier that refers to a
collection of data items that all have the same name. The data items must be of same
type (eg,, all integers, all characters, etc.). The individual data items are represented
by their corresponding array elements indicated by indexes. This is illustrated in
Fig. 1.7.
result (0)
result (1]
ie rosult [2}
CEiement } rosult [3]
result [4]
SS rout (8
result (6)
rosuit [7]
me oF
the array,
Fig. 1.7 Structure of an arrayAdvanced C Programming 1-28 Basic Elements of C
1.8.6 Variable Declarations
In C, a variable must be declared before it can be used. Variables can be declared
at the start of any block of code, but most are found at the start of each function.
Most local variables are created when the function is called, and are destroyed on
return from that function.
A declaration begins with the data type, followed by the name of one or more
variables. For example,
int high, low;
Declarations can be spread out, allowing space for an explanatory comment.
Variables can also be initialised when they are declared, this is done by adding an
equals sign and the required value after the declaration.
int high = 258; /* Maximum Temperature */
int low = -30; /* Minimum Temperature */
Variable Declarations
Declarations Comments
int x. y: ‘The unsigned variables a and b can represent values that are twice as
unsigned a, b: large as the values represented by x and y.
int count = 0.
Every time the function containing count is entered, count is set to 0.
double area Variable area has data type double.
Jong square_of_number Variable uses underscores as a word separators and has data type long
integer.
Like variables, an array must be declared before it can be used. Declaration tells
the compiler the name of the array, the type of each element and the size of element
in the array. The size of the array is constant and must be known at compilation time.
The Fig. 18 shows three different array declarations : one for integers, one for
characters and one for floating-point numbers.Advanced C Programming 1-29 Basic Elements of C
Fig. 1.8 Array declarations
Review Questions
1
1
3.
4.
5.
6
Comment on hristory of C language.
What are the general characteristics of C ?
Explain the basic structure of C program.
What are preprocessor directives ?
List the important tips to make program neat and clear.
Explain the process of editing, compiling and executing the C program.
Draw the flow chart of sequence of editing, compiling and executing C program.
1. Give the character seb of C.
What do you mean by trigraph characters ? How are they usefull ?
| List and describe various trigraph characters.
What are identifiers ?
List the rules to define vatid identifiers.
. What are keywords ?
What are constants ? How they differ from variabtes?
5. List the various types of constants with e
5. List uarious backslash character constants with the character represented by them.
7. Describe string constant.
. Explain the various data types supported by C.
What is variable ?
What is meant by value of variable ?
. Describe the array variable.
. How and where are the variables declared ?(1 = 30)Operators and Expressions
In the last chapter, we have seen constants and variables. These are the basic data
objects manipulated in a program. Declarations list the variables to be used, and state
what type they have and perhaps what their initial values are. Operators specify what
is to be done to them. Expressions combine variables and constants to produce new
values. An expression is a sequence of operands and operators that reduces to a single
value. For example,
445
is an expression whose value is 9. The value can be any type other than void.
C implements seven different expression formats, as shown in Fig. 2.1
C includes a large number of operators which fall into different categories. In this
chapter, we are going to study various operators supported by C. These are :
* Arithmetic operators
* Relational operators
* Logical operators
* Assignment operator
© Unary operators
© Conditional operators
* Bit-wise operators
We also study how these operators are used along with variables and constants to
form expressions.
(2-4)Advanced C Programming 2-2 Operators and Expressions
Primary jentifier , Constant Or Parenthetical expression
Example : 2*(a-5)
Postfix Operator
Example: a+# (Samocffectasa=a+ 1)
Unary
Example: +4 (Sameeffectas a=a+ 1)
Binary
Example: a+b
Tomary Ean]
Example: y=(f
‘Note : A comma expression is a complex expression made up of two expressions
separated by commas. It Is often used in for statement. (see chapter 5)
Fig. 2.1 C exprassion formats
2.1 Arithmetic Operators
To solve most programming problems we need to perform arithmetic operations
by writing arithmetic expressions. The Fig. 2.2 shows all the arithmetic operators
provided by C. Each operator manipulates two operands, which may be constants,
variables or other arithmetic expression. The arithmetic operators +, -,*, and / may be
used with int or double data type operands. On the other hand, the remainder
operator also known as modulus operator can be used with integer operands to find
the remainder of the division.
#include
int facto(int);
void main()
{
int iflag=0;
double angle, answer=1;
elrser();
printf("Enter the angle : ");
scanf(“%lf' ,&angle);
angle = (angle*(22.0/7.0))/180.0; /* conversion to radian */
for(i=2;i<10i=1+2)
{
if (flag==0)
{
answer = answer — pow(angle,i)/facto(i);
flag=1;
print{(%iP answer);
(A-1)Advanced C Programming A-2
Appendix -A
getch():
}
int facto(int n)
{
int i, factorial=1;
for(i=1; i<=n; i++)
{
factorial = factorial
}
return(factorial);
}
Program 2 : Checks whether string is palindrome or not.
/* Program checks whether string is palindrome or not.
“
#include
int palindrome(char s|]);
int strlen (char |);
void main()
{
char p[20];
gets(p);
if(palindrome(p))
printf("%s is a palindrome\n", p);
else
print{("%s is not a palindrome\n", p);
}
/* retums 1 ifs is a palindrome, O otherwise */
int palindrome(char s{]) {
int bottom, top;
bottom = 0;
top = strlen(s) - 1;
while(bottom < top && s[bottom]
+-+bottom;
sitopl) {
top;
}
if(bottom >= top)
return 1;Advanced C Programming A-6 Appendix -A
}
else
{
answer = answer + pow(angle,i)/facto(i);
flag=0;
}
}
print{("élfanswer);
getch();
}
int facto(int n}
factorial = factorial * i;
}
return(factorial);
}
Program 7 : Program demonstrates fe use 0
,
addresses in function
Program demonstrates the use of addresses in function arguments
fe
include
void no_swap(int x, int y);
void swap(int *p1, int *p2);
main() {
int a= 1,b = 999;
printf('a = %d,b = %d\n", a, b);
no_swap(a, b);
printfi(’a = %d, b = %d\n", a, b);
swap(&a, &b)
printi(’a = %d,b = %d\n", a, b);Advanced C Programming A-T
J* bad example of swapping - a function can't change Parameters */
void no_swap(int x, int y) {
int temp;
temp =;
x=;
y = temp;
/* good example of swapping - a function can't change parameters
but if a parameter is a pointer it can change the value it points to */
void swap(int "px, int *py) {
int temp;
temp = “px;
Program 8 ; Finds the square of array elements.
#define MAX_ROWS3
#define MAX_COLS4
void print_squarefint [ |}; /*fanction declaration */
‘void main (void)
{
int row;
int num [MAX_ROWS][MAX_COLS] =
{
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
k
for(row=0; row x[mid])
low = mid +1;
else
{
Print{("Location of target is %a, mid);
break;
/ tha termination of leap.
/* This program illustrates the use of break statement for the termination of loop
written by :
Date:
s
#include
void main()
{
int i;
for (i=
{
printf(‘%d\t",i);
if (i==10)
break;
;i < 100;i++)Advanced C Programming A-40 Appendix - A
Program 12 : Stimulates calculator.
#include
#include
#include
float add(float x,float y)
{
float z;
Zexty:
return z;
}
float sub(float x,fleat y)
{
float 2;
Bex yi
return 2;
}
float mul(float x,float y)
t
float z;
Zax"
float div(float x,loat y)
{
float z;
2=x/yi
return z;
}
float input()
{
float a;
printf("\nEnter the number:
scant("%f',&a);
return a;
}
void display(float 1)
{Advanced © Programming A-11 Appendix - A
printf("\nThe resut is: %2f".r);
}
void main()
{
int choice;
float par,
float prev = 0.0;
clrser();
printf(’..
do
{
printf(\nEnter your choice
\n1:Addition\n2:Subtraction\n3:Multiplication\n4:
scanf("ted',&choice);
switch(choice)
{
case 1:if(prevl=0)
{
printf("The first number is %f"",prev);
q=input();
t=add(prev,q);
}
else
{
p=input();
q=input();
r=add(p.q);
Program for calculator...
ivision\n§:Exit\n");
}
display(r);
preva;
break;
case 2:if(prevI=0)
{
printf(“The first number is %f:",prev);
q=input();
t=sub(prev.q);Advanced C Programming A-16 Appendix -A
char dept{12];
int sal;
char date|10};
}Employee;
/* Function Prototypes */
void addRecord(Employee);
void displayFile();
void searchRecord(Employee);
void copyRecord (Employee);
void modifyRecord(Employee);
/* For Adding New Record Into File */
void addRecord(Employee emp)
{
FILE “fp;
fp = fopen("Emp_Info.txt","a+");
printi("\a Enter Employee ID
sean{("%a",&emp id);
print{("Enter Employee Name :"};
scan{("%s",emp.name);
printi(" Enter Employee Address
scanf("%s",emp.address);
printi(" Enter Employee Department : "};
scan{("%s",emp.dept);
printi(’ Enter Employee Salary
scan{{"%d",kemp.sal};
printf(* Enter Joining Date
scanf("Xs',emp.date);
fprintf(fp ,"\n %4d %16s %15s %125 %6d
%10s',emp.idemp .name,emp.address,emp.dept,emp.sal,emp.date);
felose(fp);
/* For Displaying All Records From File */
void displayFile()
{
FILE *fp;Advanced C Programming A-18 Appendix -A
printf" %4d %1és %18s %12s %6d
%10s"emp.id,emp.name,emp.address,emp deptemp.sal,emp.date);
}
else
printf("\n Record Not Found In File’);
felose(tp):
/* To Modify An Existing Record */
void modifyRecord(Employee emp)
{
‘int key.flag:
Employee tem
FILE “fp,"fp2;
printf("\nEnter ID to Modify Record :")
scant("%d" &key);
fp = fopen(‘Emp_Info.txt',"r+");
fp2 = fopen("temp.txt'"w'};
printf("\n Enter Employee ID
scanf("%d",&temp.id);
printi(’ Enter Employee Name :");
scanf("%s",temp.name);
printf(' Enter Employee Address: ");
scanf("%s",temp. address);
printf(’ Enter Employee Department :
seanf("%s",temp.dept);
printf(' Enter Employee Salary =");
scanf(""éd",&temp. sal);
printi(' Enter Joining Date —:*};
scanf("%s",temp.date);
while(!feof{fp))
{
facanilfp,"kdks%s%e%d%s", &emp.idemp.name,emp.address,emp.dept,&emp.sal,
emp.date);
if(emp.id == key)
{