Pages

Monday, November 19, 2012

C PROGRAMMING LANGUAGE PART A.

TABLE OF CONTENTS
UNIT CHAPTER NAME PAGE NO.
SECTION - A
1 C Language 11
2 Numeric Constants and Variables 17
3 Data Input and Output 23
4 Operators and Expressions 29
5 The Decision Control & Loop Structure 35
SECTION - B
6 Arrays 45
7 Functions 51
8 Standard Library String Functions 57
9 Dynamic Data Structures in C 61
10 Structures and Union 75
11 Disk I/O Functions 83
12 Graphics Features in C 91

PREFACE
In recent years, there has been a major trend toward the use of C among serious programmers.
Among the many reasons for C’s popularity are the following :
l C is largely machine-independent. Programs written in C are easily ported from one
computer to another.
l C is widely available. Commercial C compilers are available for most personal computers,
mini-computers, and mainframes.
l C includes certain low-level features that are normally available only in assembly or
machine language.
l Programs written in C compile into smaller programs that execute efficiently.
l C is a flexible, high-level, structured programming language.
This course material provides instruction in computer programming with C. It includes complete
and understandable explanations of the commonly used features of C. In addition, the material
presents a contemporary approach to programming, stressing the importance of clarity, legibility,
modularity, and efficiency in program design. Thus, the reader is exposed to the principles of
good programming practice as well as the specific rules of C. Examples of C programs are
presented throughout the text, beginning with the first chapter. The use of an interactive
programming style is emphasized throughout the text.
This volume can be used by the beginners in the programming as well as professionals. It is
particularly well suited for an introductory programming course.
Sets of review questions and problems are provided at the end of each chapter. The review
questions enable readers to test their assimilation of the material presented within each chapter.
They also provide an effective chapter summary. The problems reinforce the principles
presented within each chapter.

SECTION - A
COMPETENCY OBJECTIVES
The objective of this Section is to provide instructions in Computer Programming with C language . It includes
complete explanations of the commonly used feature of C. At the end of the course, a student should be able
to :-
v Appreciate the flexible & structured programming of C language.
v Describe Constants & Variables used in C.
v Carry out procedures of Data input and output.
v Understand various operators and expressions used in C.
v Execute various decision controls and loop structures in C.
10
C LANGUAGE
11
C LANGUAGE
History
C was developed by Dennis Retchie in 1972 at the Bell Telephone Laboratories in U.S.A. C
was derived from a Language known as BCPL which was evolved at the Massachusetts
Institute of Technology in the late 60’s. BCPL was used to develop an operating system
known as MULTICS for early multi-user time shared computers. One of the aims of BCPL
was to achieve efficiency in compiled code. Thus BCPL was defined such that a translator
could produce efficient machine Language code. C being a successor of BCPL has a similar
philosophy. C Language has been defined so that it has the advantages of a high level language
namely machine independence. At the same time it is concise, providing only the bare
essentials required in a language so that a translator can translate it in to an efficient machine
language code. Until 1978, C was confined to use within Bell Laboratories. In 1978, when
Brian Kernighan and Ritchie published a description of the language, known as “k & rc” computer
professionals got impressed with C’s many desirable features.
By mid 1980s, popularity of C became wide spread Numerous C Compiler were written for
computers of all sizes.
This chapter Covers following Topics.
1. The structure of a C program.
2. How to develop small program in C.
3. How to input data and print the results obtained from a C program.
Structure of a C Program:-
The structure of a C program can by explained by taking an example of a C program to
calculate area and perimeter of a rectangle. The program is written as follows.
/* Example program */
/* This program finds the area and perimeter of a rectangle */
# include <stdio.h>
main( )
CHAPTER - 1
C LANGUAGE
12
C LANGUAGE
{
int p,q, area, perimeter;
p = 4
q = 6
area = p*q;
perimeter = 2 * (p+q);
printf(“area = %d\n”, area);
printf(“perimeter = % d\n”, perimeter);
}
/* End of main */
Comments
In the above program the first line in the program starts with /* and ends with */. Any thing
written between /* and */ is called a comment. In the C Language comments are an aid to the
programmer to read and understand a program. It is not a statement of the language. The
compiler ignores comments It is a good practice to include comments in a program which will
help in understanding a program.
PREPROCESSOR DIRECTIVE
Now let us observe the line
# include <stdio.h>
This is called a preprocessor directive. It is written at the beginning of the program. It commands
that the contents of the file stdio.h should be included in the compiled machine code at
the place where # include appears. The file stdio.h contains the standard input/output routines.
All preprocessor directives begin with pound sign # which must be entered in the first
column. The # include line must not end with a semicolon. Only one preprocessor directive
can appear in one line.
Main( ) Function
The next line is main( ). It defines what is known as a function in C. A C program is made up
of many functions. The function main( ) is required in all C programs. It indicates the start of a
C program. We will use main( ) at the beginning of all programs. Observe that main( ) is not
followed by a comma or semicolon.
Braces {And}
Braces{and} enclose the computations carried out by main ( ). Each line in the program is a
statement. Every statement is terminated by a semicolon; The statement itself can be written
anywhere in a line. More than one statement can be on a line as a semicolon separates them.
However it is a good practice to write one statement per line.
13
C LANGUAGE
Declaration
In the above program the first statement int p, q, area, perimeter;
This statement is called a declaration. It informs the compiler that p,q, area and perimeter are
variable names and that individual boxes must be reserved for them in the memory of the
computer. Further it tells that the data to be stored in the memory boxes named p,q, area and
perimeters are integers namely, whole numbers without a fractional part(e.g, 0,1,2,...). The
statement ends with a semicolon The effect of statement is shown in figure given below;
p q area perimeter
Fig. 1.1 Effect of defining p, q, area and perimeter as integer variable names.
Assignment Statements
The statement p=4; is an assignment statement. It commands that the integer 4 be stored in
the memory box named p. when the statement is executed the integer 4 will be stored in the
memory box named p as shown in fig. 1.2 . This statement assigns a value 4 to the variable
name p.
P
4
Fig. 1.2
The next statement q=6; assigns 6 to q
Arithmetic Statement
The statement area=p*q; is an arithmetic statement. It commands that the numbers stored in
memory boxes p and q should be copied in to the CPU. The original contents of p and q
remain in their respective boxes. These numbers are multiplied by the CPU and product is
stored in box named area. After executing this statement the box named area will contain 24
as shown in fig. 1.3.
P
P
q
q
area
area
Execution of
Statement
After executing
the Statement
4
4
6
6
6 24
24
24
*
14
C LANGUAGE
The next statement perimeter = 2 *(p+q) is also an arithmetic statement.
P q perimeter
Execution of
4 6 Statement
6 10
2
+ * 20
The next two statements in the program are commands to display the contents of memory
box named area and perimeter respectively. The library function used for display is printf( ).
the general form of this function is
printf (format string, variable 1, variable2, ——variable n);
The format string is enclosed in quotes. It specifics any message to be printed and the manner
in which the contents of variables are to be displayed for each of the variables in the list of
variables.
printf(“area = % d\n”, area);
The format string is % d\n The symbol % d says interpret the variable area occurring after the
comma in the printf statement as an integer and display its value”. The symbol \n causes the
display to advance to the next line. Thus when this statement is carried out we will see on the
screen
area = 24
After the statement
printf(“perimeter = % d\n”, perimeter);
we will have on the screen
area = 24
perimeter = 20
Some C Program Examples
Let us write a program to convert a temperature given in Celsius to Fahrenheit - The formula
for conversion is
f = 1.8C + 32
/* Example program */
/* This program converts a Celsius temperature to Fahrenheit */
# include <stdio.h>
main ( )
{
float fahrenheit, celsius;
scanf(“%f”, & celsius);
fahrenhit = 1.8*celsius + 32.0;
15
C LANGUAGE
printf (“fahrenheit = % f\n”, fahrenheit);
} /* End of main */
Note in the above program after # include we have defined the main function. If the statement.
float fahrenheit, celsius; is observed we see that
This is a declaration which informs the compiler that fahrenheit and celsius are variable names
in which floating point number will be stored. By floating point we mean a number with a
fractional part.
The statement scanf(“%f”, & celsius) is a command to read a floating point number and store
it in variable name celsius. The format string %f indicates that floating point number is to be
read. The next statement is an arithmetic statement contents of celsius is multiplied by 1.8
and added to 32.0 and stored in fahrenheit. The number 32 is written with a decimal point to
indicate that it is a floating point number. The last statement is to print the answer.
ASSIMILATION EXERCISE
Q.1 Where was C originally developed and by whom ?
Q.2 What are the major components of a C program ? What significance is attached to
name “main” ?
Q.3 How can comments be included within a C program ? Where can comments be placed?
16
C LANGUAGE
17
C LANGUAGE
CONSTANTS
The term constant means that it does not change during the execution of a program constants
may be classified as:
(i) Integer Constant
(ii) Floating point Constant
Integer Constant
Integer constants are whole numbers without any fractional parts. There are three types of
Integer constant:
(i) Decimal constant (base 10)
(ii) Octal Constant (base 8)
(iii) Hexa decimal constant(base 16)
Allowed digit in decimal constant 0,1,.2,3,4,5,6,7,8,9,. The digits of one octal constant can be
0,1,2,3,4,5,6,7 and that in hexadecimal constants are 0,1,2,3,4,5,6,7,8.9,A,B,C,D,E,F,
Rule for decimal constant
A decimal integer constant must have at least one digit and must be written without a decimal
point. The first digit in the constant should not be 0. It may have either sign + or -. If either sign
does not precede to the constant it is assumed to be positive.
Following are valid decimal integer constants:
(i) 12345
(ii) 3468
(iii) -9746
CHAPTER - 2
NUMERIC CONSTANTS AND VARIABLES
The following are invalid decimal integer constants :-
(i) 11. ( Decimal point not allowed )
(ii) 45,256(comma not allowed )
(iii) $ 125 ( currency symbol not allowed )
(vi) 025 ( first digit should not be 0 for a decimal integer )
(v) ƒ 248 ( first symbol not a digit )
Octal Constant
An octal constant must have at least one digit and start with the digit 0. It must be written
without a decimal point. It may have either sign + or -. A constant which has no sign is taken
as positive.
The following are valid octal constants.
(i) 0245
(ii) - 0467
(iii) +04013
The following are invalid octal constants
(i) 25( Does not begin with 0 )
(ii) 0387 ( 8 is not an octal digit )
(iii) 04.32 (Decimal point not allowed )
Hexadecimal constant
A hexadecimal constant must have at least one hexadecimal digit and start with Ox or OX.
It may have either sign
The following are valid hexadecimal constants
(i) OX 14 AF
(ii) OX 34680
(iii) – OX 2673E
The following are invalid hexadecimal constants:
(i) Ox14AF
(ii) OX34680
(iii) -Ox2673E
The following are invalid hexadecimal constants:
(i) 0345 (Must start of Ox)
(ii) 0x45H3 (H not a hexa decimal digit)
(iii) Hex 2345 (Ox defines a hexadecimal number, not Hex)
Floating Point Constants
A floating point constant may be written in one or two forms could fractional form or the
exponent form, the rules for writing a floating point constant in these two forms is given as
follows.
Rule (Fractional Form)
A floating point constant in a fractional form must have at least one digit to the right of the
decimal point. It may have either the + or the - sign preceding it. If a sign does not precede it
then it is assumed to be positive.
Following are valid floating point constants:
(i) 1.0
(ii) –0.5678
(iii) 5800000.0
(iv) –0.0000156
Following are invalid:
(i) 1 (Decimal point missing)
(ii) 1. (No digit following decimal point)
(iii) -1/2, (Symbol/illegal)
(iv) .5 (No digit to the left of the decimal)
(v) 58, 678.94 (Comma not allowed)
Rule (Exponential form)
A floating point constant in the exponent form consists of a mantissa and an exponent. The
mantissa must have at least one digit. It may have a sign. The mantissa is followed by the
letter E or e and the exponent. The exponent must be an integer(without a decimal point) and
must have at least one digit. A sign for the exponent is optional.
The following are valid floating point constants in exponent form:
(i) (a) 152 E08 (b) 152.0 E8 (c) 152 e+8
(d) 152 E+08 (e) 15.2 e9 (f) 1520 E7
(ii) -0.148E-5
(iii) 152.859 E25
(iv) 0.01540 e05
20
C LANGUAGE
The following are invalid:
(i) 152.AE8 (Mantissa must have a digit following).
(ii) 152*e9 (* not allowed).
(iii) +145.8E (No digit specified for exponent).
(iv) -152.9E5.5 (Exponent can not be a fraction).
(v) 0.158 E+954 (Exponent too large).
(vi) 125, 458.25 e-5 ( comma not allowed in mantissa).
(vii) 02E8 (A digit must precede in mantissa).
C Variables and Their Types
In C, a quantity which may vary during program execution is called a variable. Variable names
are names given to locations in the memory of computer where different constants are stored.
These locations can contain integer, real or character constants. In any language the types of
variables that it can support depends on the type of constants that it can handle. This is
because a constant stored in a location with a particular type of variable name can hold only
that type of constant. For example, a constant stored in a memory location with an integer
variable name must be an integer constant. One stored in location with a real variable name
must be a real constant and the one stored in location with a character variable name must be
a character constant.
Rules for Variable Names
(i) A variable name is any combination of 1 to 8 alphabets, digits or underscores.
(ii) The first character in the variable name must be an alphabet
(iii) No commas or blanks are allowed within a variable name.
(iv) No special symbol other than an underscore(as in gross-sal) can be used in a variable
name.
e.q. si_int
m_hra
pop_e_89
C compiler is able to distinguish between the variable names, by making it compulsory for you
to declare the type of any variable name you wish to use in a program. This type of declaration
is done at the beginning of the program.
21
C LANGUAGE
Following are the examples of type declaration statements:
e.q. int si, m-hra;
float bassal;
char code;
C Keywords
Keywords are the words whose meaning has already been explained to the C compiler.
Keywords can not be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer. The keywords are also
called ‘Reserved words’. There are 32 keywords available in C. following is list of keywords in
C.
auto double if static
break else int struct
case enum long typedef
const float register union
continue far return unsigned
default for short void
do goto signed white
ASSIMILATION EXERCISE
Q.1 Determine which of the following are valid identifiers. If invalid, explain why ?
(a) record 1 (b) return (c) name_and_address (d) name-and-address
Q.2 What is the range of long double?
Q.3 What are the rules for naming variables?
Q.4 Discuss the various types of constants?
22
C LANGUAGE
23
C LANGUAGE
SINGLE CHARACTER INPUT - THE getchar( ) FUNCTION
Single characters can be entered in to the computer using the C library function getchar( ).
The getchar function is a part of the standard C Language i/o Library. It returns a single
character from a standard input device. The function does not require any arguments, though
a pair of empty parentheses must follow the word getchar.
In general terms a reference to the getchar function is written as
character variable = getchar( );
Here character variable refers to some previously declared character variable
SINGLE CHARACTER OUTPUT-THE putchar( ) FUNTION
The putchar( ) function, like getchar( ), is a part of the standard C language i/o library. It
transmits a single character to a standard output device. The character being transmitted will
normally be represented as a character- type variable. It must be expressed as an argument
to the function enclosed in parentheses following the word putchar.
In general a reference to the putchar function is written as .
putchar( char var )
e.q A C-Program contains the following statement :
char C;
__ _
__ _
__ _
__ _
putchar(C);
CHAPTER - 3
DATA INPUT AND OUTPUT
24
C LANGUAGE
The first statement declares that C is a character type variable. The second statement causes
the current value of C to be transmitted to the standard output device.
ENTERING INPUT DATA THE scanf( ) FUNTION
Input data can be entered into the computer from a standard input device by means of the C
library function scanf().
In general terms, the scanf function is written as
scanf(Control string, arg1,arg2,.....,argn)
Here control string refers to a string containing certain required formatting information, and
arg1, arg2,...arg n are arguments that represent the individual input data items. The arguments
represent pointers that indicate the addresses of the data item within the computers
memory.
The control string comprises individual groups of characters with one character group for
each input data item. Each character group must begin with a a percent sign( % ). In its
simplest form a single character group will consist of the percent sign, followed by a conversion
character which indicates the type of the corresponding data item.
COMMONLY USED CONVERSION CHARACTERS FOR DATA INPUT
Conversion
character
Meaning
c data item is a single character
d data item is a decimal integer
f data item is a floating point value
h data item is a short integer
I data item is a decimal, hexadecimal or octal integer
o data item is an octal integer
s data item is a string followed by white space character
u data item is an unsigned decimal integer
x data item is a hexadecimal integer
e.q of scanf function
# include <stdio.h>
main( )
{
char item [20];
int partno;
25
C LANGUAGE
float cost;
. . .
scanf(“%s% d % f”, item, &partno, & cost);
. . .
}
The first character group % s indicates that the first argument (item) represents a string the
second character group, %d indicates that the second argument ( & partno) represents a
decimal integer value. The third character group % f, indicates that the third argument (&
cost) represents a floating point value.
e.q. consider the skeleton of the following program
# include <stdio.h>
main( )
{
char item [20];
int partno;
float cost;
. . .
scant(“%s%d%f”, item &partno, &scost);
}
The following data items could be entered from the standard input device when the program
is executed.
fastener 12345 0.05
or
fastener
12345
0.0 5
Now let us again consider the skeleton structure of a C program
# include <stdio.h>
main ( )
{
int a,b,c;
. . .
scanf (“%3d %3d %3d”, & a, & b, & c);
. . .
}
Suppose the input data items are entered as
1 2 3
Then the following assignment is will result
a = 1, b = 2, c = 3
26
C LANGUAGE
It data is entered as
123 456 789
The following assignments would be
a = 123, b = 456, c = 789
Now suppose that the data had been entered as
123456789
The assignments would be
a = 123, b = 456, c = 789
Again consider the following example
# include <stdio.h>
main ( )
{ int i ;
float x;
char c ;
. . .
scanf (“%3d %5f %c”, & i, & x, & c);
. . .
}
If the data item are entered as
10256.875 T
These when the program will be executed
10 will be assigned to i
256.8 will be assigned to x
and the character 7 will be assigned to c. the remaining two input characters(5 and T) will be
ignored.
WRITING OUTPUT DATA - THE printf( ) FUNCTION
Output data can be written from the computer on to a standard output device using the library
function printf the general form of printf function is
printf(control string, arg 1, arg 2, . . ., argn)
where control string refers to a string that contains formatting information.
arg1, arg 2, . . ., argn are arguments that represent the individual output data items.
e.g:- Following is a simple program that makes use of the printf function.
# include <stadio.h>
# include <math.h>
main ( ) /* Print several floating-point numbers */
{
27
C LANGUAGE
float i = 2.0, j = 3.0 ;
printf (“%f %f %f %f”, i, j, i+j, sqrt (i + j ));
}
Executing the program produces the following output
2.000000 3.000000 5.000000 2.236068
The gets( ) and puts( ) FUCTIONS
The gets and puts are the functions which facilitate the transfer of strings between the computer
and the standard input/output devices.
Each of these functions accepts a single argument.
The argument must be a data item that represents a string (e.g, a character array). The string
may include white space characters. In the case of gets, the string will be entered from the
keyboard and will terminate with a newline character (“i’e” the string will end when the user
presses the RETURN key).
# include <stdio.h>
main ( )
{
char line [80];
gets(line);
puts(line);
}
Now suppose following string is entered from the standard input device
I am happy
Now the output of the program will be
I am happy
ASSIMILATION EXERCISE
Q.1 A C program contains the following statements :
# include <stdio.h>
char a, b, c;
(i) Write appropriate getchar statement that will allow values for a, b and c to be entered
into the computer
(ii) Write appropriate putchar statements that will allow the current values of a,b and c
to be written out of the computer.
Q.2 When entering a string via the scanf function using an s_type conversion factor, how is
the string terminated?
Q.3 What is the purpose of the printf function? How is it used within a C program ? compare
with the putchar function ?
28
C LANGUAGE
29
C LANGUAGE
1. Arithmetic operators
There are five arithmetic operators in C . They are
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer
division.
The operator % is known as the modulus operator
e.g. Suppose that a and b are integer variables whose values are 10 and 3 respectively,
several arithmetic expressions involving these variables are shown below together with their
resulting values
Expression Value
a+b 13
a - b 7
a * b 30
a / b 3
a % b 1
Now suppose that v1 and v2 are floating - point variables whose values are 12.5 and 2.0
respectively. several arithmetic expressions involving these variables are shown below, together
with their resulting values
Expression Value
v1 + v2 14.5
v1 - v2 10.5
v1 * v2 25.0
v1 / v2 6.25
CHAPTER - 4
OPERATORS AND EXPRESSIONS
30
C LANGUAGE
Now suppose c1 and c2 are character - type variables that represent the characters P and T,
respectively. Several arithmetic expression that make use of these variables are shown below
together with their resulting values (based upon the ASCII character set)
Expression Value
C1 80
C1 + C2 164
C1 + C2 +5 169
C1 + C2 +'5' 217
P is encoded as (decimal ) 80, T is encoded as 84, and 5 is encoded as 53 in the ASCII
character set, as shown above.
Suppose that a and b are integer variables whose values are 11 and - 3, respectively. Several
arithmetic expressions involving these variables are shown below, together with their resulting
values
Expression Value
a+b 8
a-b 14
a*b -33
a/b -3
Type cast
The value of an expression can be converted to a different data type. If desired to do so the
expression must be preceded by the name of the desired data type enclosed in parentheses.
(data type) expression
This type of construction is known as a cast ( It is also called a type cast.)
Suppose that i is an integer variable whose value is 7, and f is floating- point variable whose
value is 8.5. The expression (i +f) % 4 is invalid because the first operand (i + f) is floating
point rather than integer. However the expression ((int) (i + f)) % 4 forces the first operand to
be an integer and is therefore valid, resulting in the integer remainder 3.
UNARY OPERATORS
C includes a class of operators that act upon a single operand to produce a new value such
operators are known as unary operators. Unary operators usually precede their single operands
, though some unary operators are written after their operands.
(i) UNARY MINUS
Unary minus is a unary operator where a minus sign precedes a numerical constant, a variable
or an expression. In C, all numeric constants are positive. Thus a negative number is
actually an expression consisting of the unary minus operator followed by a positive number.
31
C LANGUAGE
e.g. - 743, -0 X 7FFF, -0.2, -5E -8, -root 1, -(x +y) -3 * (x+y)
(ii) INCREMENT OPERATOR AND DECREMENT OPERATOR
The increment operator (++) causes its operand to be increased by one where as the decrement
operator causes its operand to be decreased by one. The operand used with each of
these operator must be a single variable.
e.g. Suppose i is an integer variable that has been assigned a value of 5. the expression ++i,
causes the value of i to be increased by one, Whereas the decrement operator causes the
value to be decreased by 1 so, now the new variable of i will be 4
i ++ means i = i + 1
— i means i = i-1
The increment and decrement operators can each be utilized in two different ways, depending
an whether the operator is written before or after the operand. If the operator precedes the
operand (e.g. ++ i) then the operand will be altered in value before it is utilized for its intended
purpose within the program. If however, the operator follows the operand (e.g i ++) then the
value of the operand will be altered after it is utilized
e.g. printf (“ i = %d\n”, i);
printf (“ i = % d\n”, ++i);
printf (“ i = %d\n”, i);
There printf statements will generate following three lines of out put
i = 1
i = 2
i =2
Now let us take the second case
printf (“ i = %d\n”, i);
printf (“ i = %d\n”, i++);
printf ( i = %d\n”, i )
The statement will generate the following three lines of output
i = 1
i = 1
i = 2
32
C LANGUAGE
LOGICAL OPERATORS
There are two logical operators also available in C. They are
Operator Meaning
&& and
|| or
The result of a logical and operation will be true only if both operands are true where as the
result of a logical or operation will be true if either operand is true or if both operands are true.
In other words the result of a logical or operation will be false only if both operands are false.
Suppose i is an integer variable whose value is 7, f is a floating point variable whose value is
5.5 and C is a character variable that represents the character ‘w’, several complex logical
expressions that make use of these variables are shown below:
Expression Interpretation Value
(i > = 6)&&(c = = 'w') true 1
(i >= 6)&&(c = = 119) true 1
(f < 11) && (i > 100) false 0
(c = 'p') || ((i + f) < =
10)
true 1
RELATIONAL AND LOGICAL OPERATORS
These are four relational operators in C. They are
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
EQUALITY OPERATORS
There are two equality operators in C which are as follows
Operators Meaning
= = Equal to
! = Not equal to
The six operators mentioned above are used to form logical expressions representing conditions
that are either true or false.
33
C LANGUAGE
The resulting expression will be of type integer, since true is represented by the integer value
1 and false is represented by the value 0.
e.g . Let us suppose i, j and k are integer variables whose values are 1,2 and 3 respectively.
Several logical expressions involving these variables are shown below.
Expression Interpretation Value
i < j true 1
(i + j) > = k true 1
(j + k) > (i + 5) false 0
k ! = 3 false 0
j = = 2 true 1
Expression Interpretation Value
(i > = 6)&&(c == 'w') true 1
(i > = 6) || (c = = 119) true 1
(f < 11) && (i > 100) false 0
(c1 == 'p') || ((i + f) < = 10) true 1
Both operands are true hence expression is true
Both operands are true hence expression is true
Second operand is false hence expression is false
First operand is true hence expression is true
ASSIGNMENT OPERATORS
The commonly used assignment operator is = Assignment expressions that make use of this
operator are written in the form
Identifier = expression
Here identifier represents a variable and expression represents a constant, a variable or a
more complex expression e.g. Here are some typical assignment expressions that make use
of the = operator
a = 3
x = y
sum = a+b
area = length * width.
34
C LANGUAGE
THE CONDITIONAL OPERATOR
Conditional operator is (?:) A expression that makes use of the conditional operator is called
a conditional expression
for e.g. expression 1? expression 2 : expression 3
When evaluating a conditional expression, expression 1 is evaluated first. If the expression 1
is true then expression 2 is evaluated and this becomes the value of conditional expression
However, if expression 1 is false then expression 3 is evaluated and this becomes the value
of the conditional expression e.g. In the conditional expression shown below suppose f and g
are floating point variables. The conditional expression is
(f < g)? f: g
It takes the value f if f is less than g otherwise the conditional expression takes on the value of
g. In other words conditional expression returns the value of the smaller of the two variables.
ASSIMILATION EXERCISE
Q.1 What is an operator ? Describe several different type of operator included in C.
Q.2 A C program contains the following declarations
int i, j;
long ix;
short s;
float x;
double dx;
char c;
Determine the data type of each of the following expressions,
(a) x + c (c) i + x (e) ix + 4
(b) dx + x (d) s + 4 (f) s + c
Q.3 A C program contains the following declaration and initial assignments
int i = 8, j = 5;
double x = 0.005, y = - 0.01;
char c = ‘c’, d = ‘d’;
determine the value of each of the following expressions which involve the use of
library functions
(a) abs ( i - 2 * j ) (e) log (x)
(b) abs ( x + y) (f) sqrt ( x * x + y * y)
(c) toupper (d) (g) strlen ( “ hello\ 0”)
(d) floor (x) (h) pow (x - y)
35
C LANGUAGE
The decision control structure in C can be implemented in C using
(a) The if statement
(b) The if - else statement
(c) The conditional operators
The if Statement
The general form of if statement looks like this:
if (this condition is true)
execute this statement;
Here the keyword if tells the compiler that what follows, is a decision control instruction.
The condition following the keyword if is always enclosed within a pair of parentheses. If
the condition, whatever it is true, then the statement is executed. It the condition is not true
then the statement is not executed instead the program skips past it. The condition in C is
evaluated using C’s relational operators. The relational operators help us to build expression,
which are either true or false
e.q
Expression Is true if
X = = Y X is equal to Y
X ! = Y X is not equal to Y
X <Y X is less than Y
X>Y X is greater than Y
X< = Y X is less than or equal to Y
X> = Y X is greater than or equal to Y
Demonstration of if statement
CHAPTER - 5
THE DECISION CONTROL & LOOP STRUCTURE
36
C LANGUAGE
main( )
{
int num;
printf(“Enter a number less than 10”);
scanf(“%d”, & num);
if(num < = 10)
printf(“The number is less than 10”);
}
Multiple Statements within if
If it is desired that more than one statement is to be executed if the condition following if is
satisfied, then such statements must be placed within pair of braces.
e.q The following program demonstrate that if year of service greater than 3 then a bonus
of Rs. 2500 is given to employee. The program illustrates the multiple statements used within
if
/* calculation of bonus */
main( )
{
int bonus, CY, Yoj, yr-of-ser;
printf(“Enter current year and year of joining”);
scanf(“%d %d”, &cy, &yoj);
yr-of-ser = CY-Yoj;
if(yr-of-ser > 3)
{
bonus = 2500;
printf(“Bonus = Rs. %d”, bonus);
}
}
If - else The if statement by itself will execute a single statement or a group of statements
when the condition following if is true. it does nothing when the condition is false. It the
condition is false then a group of statements can be executed using else statement. The
following program illustrates this
/* Calculation of gross salary */
main( )
{
float bs, gs, da, hra;
printf(“Enter basic salary”);
scanf(“%f”, & bs);
if(bs <1500)
{ hra = bs * 10/100;
da = bs * 90/100;
}
else
{ hra = 500;
37
C LANGUAGE
da = bs * 98/100;
}
gs = bs+hra+da;
printf(“gross salary = Rs. %f”, gs);
}
Nested if - else If we write an entire if - else construct within the body of the if statement or
the body of an else statement. This is called ‘nesting’ of ifs.
e.g.
if(condition)
{
if (condition)
do this;
else
{ do this;
and this;
}
}
else
do this;
The Loop Control structure
These are three methods by way of which we can repeat a part of a program. They are:
(a) Using a for statement
(b) Using a while statement
(c) Using a do-while statement
The while Loop:-
The general from of while is as shown below:
initialise loop counter;
while (test loop counter using a condition)
{
do this;
and this;
increment loop counter;
}
The parentheses after the while contains a condition so long as this condition remains true all
statements within the body of the while loop keep getting executed repeatedly
38
C LANGUAGE
for e.g.
/* calculation of simple interest for 3 sets of p, n and r */
main( )
{ int p,n, count;
float r, si;
count = 1;
while(count < = 3 )
{
printf(“\n Enter values of p, n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p*n*r/100;
printf(“simple interest = Rs. %f”, si);
count = count +1;
}
The do-while Loop
The do-while loop takes the following form
do
{
this;
and this;
and this;
and this;
} while (this condition is true);
There is a minor difference between the working of while and do-while loops. The difference
is the place where the condition is tested. The while tests the condition before executing any
of the statements within the while loop. As against this the do-while tests the condition after
having executed the statements within the loop.
e.g:-
main( )
{
while(5<1)
printf(“Hello \n”);
}
In the above e.q. the printf will not get executed at all since the condition fails at the first time
itself. Now let’s now write the same program using a do-while loop.
main( )
{
do
{
printf (“Hello \n”);
} while (5<1);
}
39
C LANGUAGE
In the above program the printf( ) would be executed once, since first the body of the loop is
executed and then the condition is tested.
The for Loop
The general form of for statement is as under:
for( initialise counter; test counter; increment counter)
{ do this;
and this;
and this;
}
Now let us write the simple interest problem using the for loop
/* calculation of simple interest for 3 sets of p,n and main( )
{
int p,n, count;
float r, si;
for(count = 1; count <=3; count = count +1)
{
printf(“Enter values of p,n and r”);
scanf(“%d %d %f”, & p, & n, & r);
si = p * n * r / 100;
printf(“Simple interest = Rs %f \n”, si);
}
}
The break Statement
The keyword break allows us to jump out of a loop instantly without waiting to get back to the
conditional test. When the keyword break is encountered inside any C loop, control automatically
passes to the first statement after the loop.
for e.q. The following program is to determine whether a number is prime or not.
Logic:- To test a number is prime or not, divide it successively by all numbers from 2 to one
less than itself. If the remainder of any of the divisions is zero, the number is not a prime.
40
C LANGUAGE
following program implements this logic
main( )
{
int num, i;
printf(“Enter a number”);
scanf(“%d”, &num);
i = 2
while (i < = num -1)
{
if (num%i= = 0)
{
printf(“Not a prime number”);
break;
}
i + +
}
if(i = = num)
printf(“Prime number”);
}
The continue Statement
The keyword continue allows us to take the control to the beginning of the loop bypassing the
statements inside the loop which have not yet been executed. When the keyword continue is
encountered inside any C loop, control automatically passes to the beginning of the loop. for
e.g.
main( )
{
int i,j;
for(i = 1; i< = 2; i++)
{
for(j=1; j<=2; j++)
{
if (i= =j)
continue;
printf(“\n%d%d\n”, i,j);
}
}
The output of the above program would be....
12
21
when the value of i equal to that of j, the continue statement takes the control to the for loop
(inner) bypassing rest of the statements pending execution in the for loop(inner).
41
C LANGUAGE
The Case Control structure
switch Statement:-
The switch statement causes a particular group of statements to be chosen from several
available groups. The selection is based upon the current value of an expression that is included
within the switch statement. The form of switch statement is.
switch (integer expression)
{ case constant 1:
do this;
break;
case constant 2:
do this;
break;
case constant 3:
do this;
break;
default;
do this;
}
ASSIMILATION EXERCISE
Q.1 Write a loop that will calculate the some of every third integer beginning with i = 2 ( i.e.
calculate the some 2 + 5 + 8 + 11 + ————) for all values of i that are less than 100.
Write the loop three different ways.
Q.2 Write a switch statement that will examine the value of integer variable called flag and
print one of the following messages, depending on the value assigned to flag.
(a) HOT, if flag has a value of 1
(b) LUKE WARM, if flag has value of 2
(c) COLD, if flag has value of 3
(d) OUT OF RANGE, if flag has any other value.
Q.3 Describe the output that will be generated by each of following C programs.
(a) # include <stdio.h> (b) # include < stdio.h>
main ( ) main ( )
{ {
int i = 0, x = 0; int i, j, x = 0;
while ( i < 20) { for ( i = 0; i < 5 ; ++ i)
if ( i % 5 = = 0) { for ( i = 0; j < i; ++ j) {
x + = i; x + = ( i + j - 1);
printf (“%d”, x); printf ( “ %d”, x);
} }
++i; printf (“\n x = %d”, x)
} }
printf (“ \n x = %d”, x);
}

No comments:

Post a Comment

 

Blogger news

Blogroll

About