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

UNIT – I

C Program Structure:

The C language is based on the concept of building blocks called


functions that can be held in one or more source files. Each source file is
compiled separated. A program is a collection of one or more C functions. To
write a program you first create functions and then put them together.
A function is a Subprogram that contains one or more C statements that
performs one or more tasks. In a well written C code, each function performs
only one task. Each function has a name and a list of arguments that the
function will receive.
All C programs must have a function called main ( ) and program
execution begins the execution of this function. Hence there should be only one
function called main in any C program.
C’s standard library contains many useful functions such as scanf ( ) and
printf ( ) which are used for input and output.
In addition to library functions, one can also create functions and use
them in a program. To call a function one simply writes its name as a program
statement and supply the necessary arguments.

To illustrate the general structure of a C program. Consider the following


program:
¿∗¿ This is a comment line :A sample C program ¿ /¿
{

∫ num;/¿declare num as integer ¿ /¿


printf ( Enter a number : ) ;/¿display a prompt¿ /¿

scanf (%d ,∧num); /¿readnumfrom keyboard¿ /¿

square¿ (num); /¿call a function with num as actual

parameter¿ /¿
}
¿∗¿declare the function square _ and _ print ( )∗¿

square¿ ( X) /¿ X is the formal parameter ¿ /¿

∫ X ; /¿declare the formal parameter ¿ /¿


{

∫ res ; /¿declare a local variable ¿ /¿


res=X∗X ;/¿computeres as the Square of X∗¿

printf (%d Square is %d \n , X , res);/¿display input ¿ /¿


}
The first line is a comment. In C, comments begin with the sequence ¿ /¿.
The C compiler ignores anything that is between the beginning and ending
comment symbols.
In C, blank lines are permitted and have no effect upon the program. The line
main() specifies a function with a name main.

All C programs begin execution by calling the main function. The next line
consists of a single curly brace.
{-which signifies the start of the main ( ) function.

The first line of code inside function main is


∫ num;
this line declares a variable called num and tells the compiler that num is an
integer.
In C you must declare all variables before you use them. The declaration
process involves the specification of both the type and the variables name. In
this case, num is of type int, which is C’s keyword for the integer type.
Statements are usually ended with a semicolon (;).
The second line, which displays a prompt for reading num from the keyboard is
important for two reasons. First, it is an example of a function call. Second it
illustrates the use of C’s standard output function printf ( ).
The third line actually reads an integer value for num from the keyboard using
the C’s standard input function scanf ( ).
The fourth line calls a user defined function square¿ ( ). The function
declaration places the variable X (the formal parameter) that will be receiving
the value passed to that function, inside the parenthesis that follows the function
name. Then the variable X is declared because the function must know what
type of data it will receive.
CONSTANTS, VARIABLES AND DATATYPES
The C character Set:
C uses the uppercase letters A, B, …Z, the lowercase letters a, b,…z the
digits 0 to 9 and certain special characters as building blocks to form basic
program elements (e.g., Constants, variables, operators, expressions). The
special characters are listed below:
, (comma) ∙ (period) ; (semicolon)

: (colon) ? (question mark) ' (apostraophe)

! (exclamation mark)| (vertical bar) ¿ (slash)

¿ (back slash) (tilde) ¿(underscore)


$ (dollar sign) % (percent sign) ¿(number sigh)

¿(ampersand)¿(caret) ¿ (asterisk)

−¿ (minus sign) +¿ (plus sign) ¿ (less than)

¿ (greater than) ¿ (equal sign) ( (left parenthesis)


¿ (right parenthesis) ¿ (left bracket) ¿ (right bracket)

{ (left brace) } (right brace)

White spaces: Blank space, Horizontal tab, Carriage return, Newline, Form
feed.
Trigraph Characters:
Many non-English keyboards do not support all the characters mentioned
above ANSI C introduces the concept of “trigraph” sequences to provide a way
to enter certain characters that are not available on some keyboards. Each
trigraph sequence consists of three characters (two question marks followed by
another character) as shown in table below:
Trigraph Sequence Translation
? ?=¿ ¿ number sign
?? ¿ ¿ left bracket
?? ¿ ¿ right bracket
? ? <¿ { left brace
? ? >¿ } right brace
?? ! ¿ vertical bar
??/¿ ¿ back slash
? ?' ¿ caret
? ?−¿ tilde
C Tokens:

In a passage of text, individual words and punctuation marks are called


tokens. Similarly, in a C program the smallest individual units are known as C
tokens. C has six types of token as shown in fig. below:

C TOKENS

Keywords Constants Strings Operators

Identifiers Special Symbols

Keywords and Identifiers:


There are certain reserved words called keywords that have standard,
predefined meanings in C. These keywords can be used only for their
intendedpurpose; they cannot be used as programmer – defined identifiers.
The standard keywords are:

auto double init 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 are names given to various programs elements, such as


variables, functions and arrays. Identifiers consist of letters and digits in any
order, except that the first character must be a letter. Both upper and lower case
letters are permitted. Uppercase and lowercase are not interchangeable (i.e., an
uppercase letter is not equivalent to the corresponding lowercase letter).
The underscore character ( _ ) can also be included and is considered to
be a letter. An underscore is often used in the middle of an identifier. An
identifier may also begin with an underscore.
Example:

The following names are valid identifiers:


X y12 _ temperature Items_Counted test123
TABLE Sum_ 1
The following names are not valid identifiers:
1Count – the first character must be a letter
“X” - illegal character (“)
Order - no – illegal character ( - )
Two word – illegal character (blank space)
DATA TYPES:
In C, the following five basic data types are offered:

Data type Description


int integer quantity
char single character
floating – point number
float ( i.e. a number containing a decimal point and or an
exponent)
double – precision floating – point number
double ( i.e. more significant figures and an exponent which
may be larger in magnitude)
void Valueless

Type modifiers (Qualifiers):


Except for void, the basic data types may have various type modifiers
(qualifiers) that precede them. A type modifier (qualifier) is used to alter the
meaning of the basic type to fit the needs of various situations more precisely.
The following is the list of the type modifiers (qualifiers) used in C:
signed
unsigned
long
short.
The modifiers signed, unsigned, long and short are applied to character
and integer base type. The modifier long alone may be applied to double. The
following table lists the possible combinations of C’s base types and modifiers
along with their bit width and range of values.
Type Size (Bit width)
char or signed char 8
unsigned char 8
int or signed int 16
unsigned int 16
short int or signed short int 8
unsigned short int 8
long int or signed long int 32
unsigned long int 32
float 32
double 64
long double 80

CONSTANTS:
In C, Constants refer to fixed values that the program may not alter, C
constants can be of any of the basic data types. i.e., C has four basic types of
constants. They are integer constants, floating point constants, character
constants and string constants.
Integer and floating – point constants represent numbers. They are
referred to as numeric type constants.
The following rules apply to all numeric – type constants:
1. Commas and blank spaces cannot be included with in the constant.
2. The constant can be preceded by a minus (–) sign if desired.
3. The value of a constant cannot exceed specified minimum and maximum
bounds.
1. Integer Constants
An integer constant is an integer – valued number. Thus it consists of a
sequence of digits. Integer constant can be written in three different number
systems: decimal (base 10), Octal (base 8) and hexadecimal (base 16).
A decimal integer constant can consist of any combination of digits taken
from the set 0 through 9. If the constant contains two or more digits the first
digit must be something other than 0.
Example:
0 1 743 5280 32767 99999
The following decimal integer constants are written incorrectly:
12,245 Illegal character ( , )
36.0 Illegal character (.)
10 20 30 Illegal character ( blank space)
123 – 45 – 689 Illegal character ( – )
0900 The first digit cannot be a zero
An Octal integer constant can consists of any combination of digits taken
from the set 0 through 7. However, the first digit must be 0, in order to identify
the constant as an octal number.
Example: 0 01 0743 07777
The following are the invalid octal integer:
743 Does not begin with 0
05280 Illegal digit (8)
0777.777 Illegal character (.)

A hexadecimal integer constant must begin with either ox or OX. It can


be followed by any combination of digits taken from the sets 0 through 9 and a
through f (either upper case or lower case). Note that the letters a through f (or
A through F) represent the (decimal) quantities 10 through 15 respectively.
Example: ox OX1 OX7FFF oxabcd
The following are the invalid hexadecimal integer:
OX12.34 Illegal character (.)
OBE38 Does not begin with ox or OX
ox.4bff Illegal character (.)
OXDEFG Illegal character (G)

Unsigned and Long integer constants:


An unsigned integer constant can be identified by appending the letter U
(either upper case or lower case) to the end of the constant.
To create a long integer constant by appending the letter L (either upper
case or lower case) to the end of the constant.
An unsigned long integer may be specified by appending the UL to the
end of the constant. The letter may be written in either upper or lower case.
However the U must precede the L.
Example:
Constant Number System
50000U Decimal (unsigned)
123456789L Decimal (long)
123456789UL Decimal (unsigned long)
O123456L Octal (long)
O777777U Octal (unsigned)
OX50000U hexadecimal (unsigned)
OXFFFFFUL hexadecimal (unsigned long)

2. Floating – Point Constant:


A floating – point constant is a base-10 number that contains either a
decimal point or an exponent or both.
Example:
0. 1. 0.2 827.602 50000. 0.000743 12.3
315.0066
2E–8 0.006e–3 1.6667E+8 .12121212e12
The following are not valid floating – point constants:
Either a decimal point or an exponent must
1
be present
1,000.0 Illegal character ( , )
The exponent must be an integer quantity
2E+10.2
(it cannot contain a decimal point)
Illegal character (blank space) in the
3E 10
exponent

The interpretation of a floating – point constant with an exponent is


essentially the same as for scientific notation, except that the base 10 is replaced
by the letter E (or e). thus the number 1.2×10-3 would be written as 1.2E-3 or
1.2e-3. This is also equivalent to 0.12e-2 or 12e-4 etc.
Example:
The quantity 3×105 can be represented in C by any of the following
floating – point constants.
300000. 3e5 3e+5 3E5 3.0e+5
.3e6 0.3E6 30E4 30.E+4 300e3
Similarly, the quantity 5.026×10-17 can be represented by any of the following
floating – point constants:
5.026E–17 .5026e–16 50.26e–18 .0005026E–13
Floating – point constants are normally represented as double – precision
quantities in C. Hence each floating – point constant will typically occupy 2
words (8 bytes) of memory.
3. Character Constants:
A character constant is a single character enclosed in apostrophes (single
quotation marks).
Example:
‘a’ ‘5’ ‘r’ ‘<’ ‘In’ ‘A’ ‘$’ ‘’
The last constant consists of a blank space enclosed in apostrophes.
4. String Constants:
A string constant consist of any number consecutive characters (including none)
enclosed in (double) quotation marks.
Example:
“green” “C learning is interesting” “270-32-3456”
“$19.95” “2*(I+3)/J” “ ” “Line1/ n Line2/ nLine3”“”
Note that the string constant “Line1/ n Line2/ nLine3” extends over three
lines, because of the new line characters embedded with in the string. Thus this
string would be displayed as
Line 1
Line 2
Line 3
Also notice that the string “ ” is a null (empty) string.
Escape Sequences:
Certain non printing characters, as well as the double quote (“), the
apostrophe (‘), the question mark (?)and the back slash ( \ ) can be expressed in
terms of escape sequences. As escape sequences always begins with a back
ward slash and is followed by one or more special characters.
These escape characters are listed below:
Character Meaning
\b Back space
\f Form feed
\n New line
\r Carriage return
\v Vertical tab
\\ Back slash
\” Double quote
\’ Single quote
\(carriage return) Line continuation
\nnn Octal character value
\a Bell (alert)

VARIABLES:
A variable is an identifier that is used to represent some specified type of
information within a designated portion of the program.
In its simplest form, a variable represents a single data item that is a numerical
quantity or a character constant. The data item must be assigned to the variable
at some point in the program. The data item can be accessed later in the
program. Simply by referring to the variable name.
The variables of a particular basic data type can be declared using the following
format:
type – identifier variable – list;
Example:
inta,b,c;
char d;
Here a, b and c each represent an integer – valued quantity and d represent a
single character.
Arrays:
An array is an identifier that refers to a collection of data items which all
have the same name. The data items must be all of the same type. The
individual data items are represented by their corresponding array elements. The
individual array elements are distinguished from one another by the value that is
assigned to a subscript.
Example:
Suppose that X is an 10-element array. The first element is referred to as
X[0], the second as X[1] and so on. The last element will be X[9]. The subscript
associated with each element is shown in square brackets. Thus the value of the
subscript for the first element is 0, the value of the subscript for the second
element is 1 and so on. For an n-element array, the subscript always range from
0 to n-1.
There are several different ways to categorize arrays:
Firs we shall discuss the one-dimensional character array often called a
char – type array. This type of array is generally used to represent a string. Each
array element will represent one character within the string.
Since the array is one dimensional, there will be a single subscript
(sometimes called an index) whose value refers to individual array elements. If
the array contains n elements, the subscript will be an integer quantity whose
values range from 0 to n-1. Note that an n-character string will require an (n+1)
element array, because of the null character (∖ ϕ) automatically placed at the end
of the string.
Examples:
Suppose the string “TIRUCHIRAPPALLI” is to be stored in a one –
dimensional array called letter. Since “TIRUCHIRAPPALLI” contains 15
characters, letter will be an 16-element array. Thus letter[0] will represent the
letter T, letter[1] will represent I and so on, as summarized below. Note that the
last (i.e. the 16th) array element, letter[15] represents the null character which
signifies the end of the string.
Element Corresponding data item
Subscript Value Array Element
Number (String character)
1 0 letter [0] T
2 1 letter [1] I
3 2 letter [2] R
4 3 letter [3] U
5 4 letter [4] C
6 5 letter [5] H
7 6 letter [6] I
8 7 letter [7] R
9 8 letter [8] A
10 9 letter [9] P
11 10 letter [10] P
12 11 letter [11] A
13 12 letter [12] L
14 13 letter [13] L
15 14 letter [14] I
16 15 letter [15] ∖ϕ

The array elements and their contents are shown schematically as below:
T I R U C H I R A P P A L L I ∖ϕ
Subscript 1 1 1
0 1 2 3 4 5 6 7 8 9 11 14 15
value 0 2 3

DECLARATIONS:
A declaration associates a group of variables with a specific data type. All
variables must be declared before they can appear in executable statements.
A declaration consists of a data type, followed by one or more variable
names, ending with a semi-colon. Each array variable must be followed by a
pair of square brackets, containing a positive integer which specifies the size
(i.e. the number of elements) of the array.
Example:
1. A C program contain the following type declarations:
int a, b, c;
float root1, root2;
char flag, text[80];
Here a, b and c are declared to be integer variables, root1 and root2 are floating
point variables, flag is char-type array. Here the square brackets enclosing the
size specification for text. These declarations could also have been written as
follows:
int a;
int b;
int c;
float root1;
float root2;
char flag;
char text[80];
Remark:
Integer – type variables can be declared to be short integer for smaller
integer quantities or long integer for longer integer quantities. Such variables
are declared by writing short int and long int or simply short and long
respectively.
2. A C program contains the following type declarations:
shortint a, b, c;
longint r, s, t;
int p, q;
some compilers will allocate less storage space to the short integer variable a, b
and c than to the integer variables p and q. typical values are 2 bytes for each
short integer variable and 4 bytes (1 word) for each ordinary integer variable.
Similarly some compilers will allocate additional storage space to the
long integer variables r, s and t than to the integer variables p and q. Typical
values are 2 words (8 bytes) for each long integer variables and 1 word (4 bytes)
for each ordinary integer variable. The maximum permissible values of r, s and t
will be larger than the maximum permissible values of p and q when using one
of these compilers.
The above declarations can be written as
short a, b, c;
long r, s, t;
int p, q;
thus short and short int are equivalent, as are long and long int.
An integer variable can also be declared to be unsigned, by writing
unsigned int or simply unsigned. Unsigned integer quantities can be larger than
ordinary integer quantities but they cannot be negative.
3. A C program contains the following type declarations:
int a, b;
unsigned x, y;
The unsigned variables x and y can represent values that are
approximately twice as large as the values represented by a and b. However x
and y cannot represent negative quantities.
Floating – point variables can be declared to be double precision by using
the type indicator double or long float rather than float.
4. A C program contains the following type declaration:
int c = 12;
char star = ‘*’;
float sum = 0;
double factor = 0.21023e-6;
5. A C program contains the following type declaration:
char text[] = “TIRUCHIRAPPALLI”;
This declaration will cause text to be an 16 – element character array. The first
15 elements will represent the 15 characters within the word
TIRUCHIRAPPALLI and the 16th element will represent the null character
which is automatically added at the end of the string.
The above declaration can also be written as
char text[16] = “TIRUCHIRAPPALLI”;
Suppose if the size is too small for example
char text[15] = “TIRUCHIRAPPALLI”;
The characters at the end of the string (in this case, the null character) will be
lost.
Suppose, if the size is too large, for example
char text[20] = “TIRUCHIRAPPALLI”;
The extra array elements may be assigned zeros or they may be filled with
meaningless characters.
User – Defined Type Declaration:
C supports a feature known as “type definition” that allows users to
define an identifier that would represent an existing data type. Its general form:
typedef type identifier;
where type refers to an existing data type and “identifier” refers to the “new”
name given to the data type. Remember that the new type is “new” only in
name, but not the data type.
Example:
typedefint units;
typedef float marks;
Here units symbolizesint and marks symbolizes float. They can be later used to
declare variables as follows:
units batch1, batch2;
marks name1[50], name2[50];
batch1 and batch2 are declared as int variable and name1[50] and name2[50]
are declared as 50 element floating point array variables. The main advantage of
typedef is that we can create meaningful data type names for increasing the
readability of the program.
Another user – defined data type is enumerated data type provided by
ANSI standard. It is defined as follows:
enum identifier {value1, value 2, … value n};
Example:
enum day {Monday, Tuesday, …. , Sunday};
enum day week_st, week_end;
Declaration of Storage Class:
Variables in C can have not only data type but also storage class that
provides information about their location and visibility. The storage class
decides the portion of the program with in which the variables are recognized.
Consider the following example:
/* Example of storage classes*/
int m;
main()
{
int i;
float balance;
…………….
…………….
function1();
}
function1()
{
int i;
float sum;
…………….
…………….
}
The variable m which has been declared before the main is called global
variable. It can be used in all the functions in the program. It need not be
declared in other functions. A global variable is also known as an external
variable.
The variables I, balance and sum are called local variables because they
are declared inside a function. Local variables are visible and meaningful only
inside the functions in which they are declared. They are not known to other
functions. Note that the variable i has been declared in both the functions. Any
change in the value of i in one function does not affect its value in the other.
C provides a variety of storage class specifiersthat can be used to declare
explicitly the scope and lifetime of variables.
Storage class Meaning
Local variable known to only to the function in
auto
which it is declared. Default is auto.
Local variable which exists and retains its value
static even after the control is transferred to the
calling function.
Global variable known to all functions in the
extern
file
register Local variable which is stored in the register
Expressions:
An expression represents a single data item such as a number or
character. The expression may consist of a single entity, such as a constant, a
variable, an array element or a reference to a function. It may also consist of
same combination of such entities inter connected by one or more operators.
Expression can also represent logical conditions that are either true or
false. However, in C the conditions true and false are represented by the integer
values 1 and 0 respectively.
Example:
a+b
x=y
c=a+b
x<=y
x==y
++i
The first expression involves use of the addition operator (+). The expression
represents the sum of the values assigned to the variables a and b.
The second expression involves the assignment operator (=). In this case, the
expression cause the value represented by y to be assigned to x.
The third expressions continues the features of first two expressions. In this
case, the value of the expression a + b is assigned to the variable c.
The fourth expression will have the value1 (true) if the value of x is less than or
equal to the value of y. Otherwise the expression will have the value ϕ (false).
In this expression, < = is a relational operator that compares the values of the
variables x and y.
The fifth expression is a test for equality and the last operator ++ which
indicates incrementing is called a unary operator. i.e. This expression causes the
value of the variable i to be increased by 1 (i.e. incremented) which is
equivalent to i = i + 1.

STATEMENTS:
A statement causes the computer to carry out some action. There are three
different classes of statement in C. they are expression statements, compound
statements and control statements.
An expression statement consists of an expression followed by a
semicolon.
Example:
a = 3;
c = a + b;
++i;
printf(“Area = %f ”, area);
Here the first two expression statements are assignment – type statements. Each
causes the value of the expression in the right of the equal sign to be assigned to
the variable on the left. The third expression statement is an incrementing type
statement which cause the value of i to increase by 1.
The fourth expression statement causes the printf function to be
evaluated. This is a standard C library function that writes information out of
the computer. In this case, the message Area = will be displayed, followed by
the current value of the variable area.
Compound statement consists of several individual statements enclosed
within a pair of braces ( { and } ). The individual statements may themselves be
expression statements, compound statements or control statements. Thus the
compound statement provides capability for embedding statements within other
statements. Unlike an expression statement a compound statement does not end
with a semicolon.
Example:
{
pi = 3.141596;
circumference = 2*pi*radius;
area = pi*radius*radius;
}
This particular compound statement consists of three assignment type
expression statements. Note that the compound statement does not end with a
semicolon after the brace.
Control statements are used to create special program features, such as
logical tests, loops and branches.
Example:
while (count <=n) {
printf(“x=”);
scanf(“%f ”, &x);
sum + = x;
+ + count;
}
Symbolic Constants:
A symbolic constant is a name that substitutes for a sequence of
characters. The characters may represent a numeric constant, a character
constant or a string constant. Thus a symbolic constant allows a name to appear
in place of a numeric constant, a character constant or a string. When a program
is compiled each occurrence of a symbolic constant is replaced by its
corresponding character sequence.
Symbolic constants are usually defined at the beginning of a program.
The symbolic constants may appear later in the program in place of numeric
constants, character constants and so on. A symbolic constant is defined by
writing
# define name text.
Where name represents a symbolic name typically written in uppercase letters
and text represents the sequence of characters associated with the symbolic
name. Note that text does not end with a semicolon since a symbolic constant
definition is not a true C statement. More over if text were to end with a
semicolon, this semicolon would treated as though it were a part of the numeric
constant, character constant or string constant that is substituted for the
symbolic name.
Example:
A C program contains the following symbolic constant definitions:
# define TAXTRATE 0.23
# define PI 3.141593
# define TRUE 1
# define FALSE 0
# define FRIEND “RAJA”
The following are the examples of invalid # define statements:
Statement Validity Remark
#define X = 2.5 Invalid ‘=’ sign is not allowed
No white space between # and
# define MAX 10 Invalid
define
#define N 25; Invalid No semicolon at the end
#define N5, M10 Invalid A state can define only one name
Define should be in lower case
#Define ARRAY 11 Invalid
letters
#define PRICE$ 100 Invalid $ symbol is not permitted in name

OPERATORS AND EXPRESSIONS


An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C operators can be classified into a
number of categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment & Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
ARITHMETIC OPERATORS:
There are five arithmetic operators in C.
They are:
+ addition or unary plus
– subtraction or unary minus
* multiplication
/ division
% modulo division or remainder after integer division
The operands acted upon by arithmetic operators must represent numeric
values. Thus the operands can be integer quantities, floating – point quantities
or characters. The remainder operator (%) requires that both operands be
integers and the second operand be non-zero. Similarly the division operator (/)
requires that the second operand be non-zero, though the operandneed not be
integers.
Division of one integer quantity by another is referred to as integer
division. This operation always portion of the quotient (i.e. the decimal portion
of the quotients). On the other hand if a division operator is carried out with two
floating point numbers or with one floating point number and one integer, the
result will be a floating point quotient.
Examples:
1. Integer Arithmetic:
Suppose a and b are integer variables whose values are 10 and 3
respectively. Several arithmetic expressions involving these variables are shown
below:
Expression Value
a+b 13
a–b 7
a*b 30
a/b 3
a%b 1

2. Real Arithmetic:
Suppose a and b are floating point variables whose values are 12.5 and
2.0 respectively. Several arithmetic expressions involving these variables are
shown below:
Expression Value
a+b 14.5
a–b 10.5
a*b 25.0
a/b 6.25
The operator % cannot be used with real operands.
3. Mixed – mode arithmetic:
Suppose that a is an integer variable whose value is 7 and b is an floating
point variable whose value is 8.5.
The expression (a + b)% 4 is invalid because the first operand (a + b) is floating
point rather than integer.
However (int (a + b))% 4 is valid, resulting in the integer remainder 3.
4. Suppose that a and b are integer variable 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
a%b 2
If a = –11 and b = 3 then
a/b –3
a%b –2
If a = –11 and b = –3 then
a/b 3
a%b –2

Relational Operators:
The following are the relational operators in C:
Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
The associativity of these operators is left – to – right. These six operators
are used to form logical expressions representing conditions that are either true
or false. The resulting expressions will be of type integer, since true is
represented by the integer value 1 and false is represented by the value ϕ .
Example:
1. suppose that 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 ϕ
k != 3 false ϕ
j==2 true 1

2. Suppose that 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.

Expression Interpretation Value


f>5 true 1
(i + f) <= 10 false ϕ
c = =119 true 1
c != ‘p’ true 1
c > = (ϕ *(i + f)) false 0

LOGICAL OPERATORS:
C has the following three logical operators:
Operator Meaning
&& logical AND
|| logical OR
! logical NOT

The result of a logical AND operation will be true only if both operands
are true whereas 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.
Example:
1. Suppose that 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’.
Expression Interpretation Value
(i > = b) && (c = = ‘w’) true 1
(i > = b) || (c = = 119) true 1
(f < 11) && (i > 100) false ϕ
(c! = ‘p’) || ((i + f) < = 10) true 1
The first expression is true because both operands are true. In the second
expression, both operands are again true hence the overall expression is true.
The third expression is false because the second operand is false. Finally the
fourth expressions is true because the first operands is true.
2. Suppose that i is an integer variable whose value is 7, f is a floating – point
variable whose value is 5.5
Expression Interpretation Value
f>5 true 1
! (f > 5) false ϕ
i<=3 false ϕ
!( i < = 3) true 1
i > (f + 1) true 1
! (i > (f + 1)) false ϕ

INCREMENT AND DECREMENT OPERATORS:


C has useful operators not generally found in other languages. These are
the increment and decrement operators:
+ + and – –
The increment operator causes its operand to be increased by one where
as the decrement operator causes its operand to be decreased by one.
Both are unary operators and take the following form.
+ + i or i + +
– –i or i – –
+ + i is equivalent to i = i + 1 or i + = 1
– – i is equivalent to i = i – 1 or i – = 1
To understand the difference between + + i and i + +.
Consider the following example:
i=5
y=++i
In this case, the value of y and i would be 6.
Suppose i=5
y=i++
then the value of y would be 5 and i would be 6.
Hence a prefix operator (+ + i) first adds 1 to the operand and then the
result is assigned to the variable on left. On the other hand, a postfix operator (i
+ +) first assigns the value to the variable on left and then increments the
operand.

ASSIGNMENT OPERATORS:
These are several different assignment operators in C. All of them are
used to form assignment expression which assigns the value of an expression to
an identifier. The most commonly used assignment operator is =. The general
form of an assignment expression is
identifier = expression
where identifier represents a variable and expression represents a constant, a
variable or a more complex expression.
Example:
1. Suppose i is an integer – type variable
Expression Value
i = 3.9 3
i = –3.3 –3

2. Suppose that i and j are both integer type variables and that j has been assigned
a value of 5.
Expression Value
i=j 5
i=j/2 2
i=2*j/2 5 (left to right associativity)
4 (truncated division, followed by
i =2* ( j / 2)
multiplication)

C contains the following five additional assignment operators:


+= –= *= /= %=
The assignment expression expression1 + = expression2is equivalent to
expression1 = expression1 + expression2
and so on for all remaining operators.
Example:
1. Suppose that i and j are integer variables whose values are 5 and 7 and f and
g are floating – point variables whose values are 5.5 and – 3.25.
Equivalent
Expression Final Value
Expression
i+=5 i=i+5 10
f–=g f=f–g 8.75
j * = (i – 3) j = j * (i – 3) 14
f/=3 f=f/3 1.833333
i % = (j - 2) i = i % (j - 2) 0

2. Suppose that x, y and z are integer variables which have been assigned the
values 2, 3 and 4 respectively
The expression x*= –2*(y + z)/3
is equivalent to the expression x = x * (–2*(y + z)/3) = –8
Here the expression (y + z) will be evaluated first resulting in 7. Then the value
of this expression will be multiplied by –2 yielding –14. This product will be
divided by 3 we get –4, omit the decimal and then multiplied by the original
value of x (i.e. 2) to yield the final result of –8.

THE CONDITIONAL OPERATOR:


A ternary operator pair “?:” is available in C to construct conditional
expressions of the form:
expression1? expression2: expression3.
When evaluating a conditional expression, expression1 is evaluated first.
If expression1 is true (i.e. if its value is non-zero) then expression2 is evaluated
and this becomes the value of the conditional expression. However if
expression1 is false (i.e. if its value is zero) then expression3 is evaluated and
this becomes the value of the conditional expression. Note that only one
expressions (either expression2 or expression3) is evaluated when determining
the value of a conditional expression.
Example:
Suppose i is an integer variable: (i <ϕ ) ? ϕ : 100
The expression (i <ϕ ) is evaluated first. If it is true the entire conditional
expression takes on the value ϕ . Otherwise takes on the value 100.
BITEWISE OPERATORS:
C has a distinction of supporting special operators known as bitwise
operators for manipulation of data at bit level. These operators are used for
testing the bits or shifting them right or left. Bitwise operators may not be
applied to float or double.The following are the lists of bitwise operators and
their meanings:
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one's complement

SPECIAL OPERATORS:
C supports some special operators such as comma operator, size of
operator, pointer operators (& and *) and member selection operators (. and ⟶
).
The comma operator:
The comma operator can be used to link the related expressions together.
A comma – linked list of expressions are evaluated left to right and the value of
right – most expression is the value of the combined expression.
For example, value = (x = 10, y = 5, x + y);
Here value = 15.
The size of operator:
The size of operator is normally used to determine the lengths of arrays
and structures when their sizes are not known to the programmer. It is also used
to allocate memory space dynamically to variables during execution of a
program.
Example:
m = size of (sum);
n = size of (long int);
k = size of (235L);
ARITHMETIC EXPRESSIONS:
An arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of the language.
Expressions are evaluated using an assignment statement of the form:
variable = expression;
For example,
x = a * b – c;
y = b/c * a;
z = a – b/c +d;
Precedence of Arithmetic operators:
An arithmetic expression without parenthesis will be evaluated from left to right
using the rules of precedence of operators.
High priority * / %
Low priority + –
Example:
1. Suppose a = 9, b = 12, c = 3 then find
x=a–b/3+c*2–1
y = a – b / (3 + c) * (2 – 1)
z = a – (b / (3 + c) * 2) – 1
Now,
x = 9 – 12 / 3 + 3 * 2 – 1
=9–4+6–1
= 5 + 5 = 10
y = 9 – 12 / (3 + 3) * (2 – 1)
= 9 – 12 / 6 * 1
= 9 – 12 / 6
=9–2=7
z = 9 – (12 / (3 + 3) * 2) – 1
= 9 – (12 / 6 * 2) – 1
= 9 – (12 / 12) – 1
=9–1–1=7
Type Conversions in Expressions:
C permits mixing of constants and variables of different types in an
expression.
The following are the sequence of rules that are applied while evaluating
expressions:
All short and char are automatically converted to int then:
1. if one of the operands is long double, the other will be converted to long
double and the result will be long double.
2. else, if one of the operands is double, the other will be converted to double
and the result will be double.
3. else, if one of the operands is float, the other will be converted to float and
the result will be float.
4. else, if one of the operands is unsigned long int the other will be converted to
unsigned long int and the result will be unsigned long int.
5. else, if one of the operands is long int and the other is unsigned int then:
a) if unsigned int can be converted to long int, the unsigned int operand will
be converted as such and the result will be long int.
b) else both operands will be converted to unsigned long int and the result
will be unsigned long int.
6. else, if one of the operands is long int the other will be converted to long int
and the result will be long int.
7. else, if one of the operands is unsigned int, the other will be converted to
unsigned int and the result will be unsigned int.
Casting a value:
The process of a local conversion is known as casting a value. The general
format is
(type – name) expression
Where type – name is one of the standard data types, the expression may be a
constant, variable or an expression.
Example:
1. x = (int) 7.5 7.5 is converted to integer by truncative
2. a = (int) 21.3 / (int) Evaluated as 21/4 and the result would
4.5 be 5
3. b = (double) sum/n Division is done in floating point mode
4. y = (int) (a + b) The result of a + b is converted to integer
5. z = (int) a + b a is converted to integer and then added
to b
6. p = cos ((double)x) Converts x to double before using it

Mathematical Functions:
Mathematical functions such as cos, sqrt, log, etc, are frequently used in
analysis of real – life problems. Most of the C compilers support these basic
math functions. When we use any of these functions in the program we must
include the line:
# include <math.h>
Function Meaning
Trigonometric
a cos(x) Arc cosine of x
a sin(x) Arc sine of x
a tan(x) Arc tangent of x
a tan2(x, y) Arc tangent of x/y
cos(x) cosine of x
sin(x) sine of x
tan(x) tangent of x
Hyperbolic:
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x
tanh(x) Hyperbolic tangent of x
Other functions:
ceil(x) X rounded up to the nearest integer
exp(x) e to the power x (ex)
fabs(x) Absolute value of x
floor(x) x rounded down to the nearest integer
fmod(x, y) Remainder of x | y
log(x) Natural log of x, x > 0
log 10 (x) Base 10 log of x, x > 0
pow(x, y) x to the power y (xy)
sqrt(x) Square root of x, x > = 0
Remark:
1. x and y should be declared as double.
2. In trigonometric and hyperbolic functions x and y are in radians.
3. All the functions return a double.
Example:
1. Write a C program to the message “I see, I remember”.
Solution:
#include<stdio.h>
main ()
{
printf(“I see, I remember”);
}
2. Write a C program to add two numbers.
Solution:
#include<stdio.h>
main ()
{
int number;
float amount;
number = 100;
amount = 30.75 + 75.35;
printf(“%d \n”, number);
printf(“%5.2f ”, amount);
}
3. Write a C program to find the interest for the given principal amount.
Solution:
#include<stdio.h>
#define PERIOD 10
#define PRINCIPAL 5000.00
main ()
{
int year;
float amount, value, inrate;
amount = PRINCIPAL;
inrate = 0.11;
year = 0;
while(year <= PERIOD)
{
printf(“%2d %8.2f\n”, year, amount);
value = amount + inrate * amount;
year = year + 1;
amount = value;
}
}
Output:
0 5000.00
1 5550.00
2 6160.50
3 6838.15
4 7590.35
5 8425.29
6 9352.07
7 10380.80
8 11522.69
9 12790.19
10 14197.11

4. Write a C program to calculate the cosine values for angles 0, 10, 20, …. 180.
Solution:
#include<stdio.h>
#include<math.h>
#define PI 3.1416
#define MAX 180
main ()
{
int angle;
float x, y;
angle = 0;
printf(“ Angle cos(angle)\n\n”);
while(angle <= MAX)
{
x = (PI / MAX) * angle;
y = cos(x);
printf(“%15d %13.4f \n”, angle, y);
angle = angle + 10;
}
}
Output:
Angle cos(angle)
0 1.0000
10 0.9848
20 0.9397
30 0.8660
40 ⋮
50 ⋮
⋮ ⋮
⋮ ⋮
⋮ ⋮
180 – 1.0000
5. Write a C program to show declarations, assignments and values stored in
various types of variables.
# include <stdio.h>
main ()
{
float x, p;
double y, q;
unsigned k;
int m = 54321;
longint n = 1234567890;
x = 1.234567890000;
y = 9.87654321;
k = 54321;
p = q = 1.0;
printf(“m = %d \n”, m);
printf(“n = %d \n”, n);
printf(“x = % .12 lf\n”, x);
printf(“x = % f\n”, x);
printf(“y = % .12 lf\n”, y);
printf(“y = % lf\n”, y);
printf(“k = %u p = %f q = % .12 lf \n”, k, p, q);
}
Output:
m = – 11215
n = 1234567890
x = 1.234567880630
x = 1.234568
y = 9.876543210000
y = 9.876543
k = 54321 p = 1.000000 q = 1.000000000000

6. Write a C program to illustrate the use of scanf function.


Solution:
# include <stdio.h>
main ()
{
int number;
printf(“Enter an integer number \n”);
scanf(“%d”, &number);
if (number < 100)
printf(“ Your number is smaller than 100 \n\n”);
else
printf(“ Your number contains more than two digits \n”);
}
7. Write a C program to calculate the interest rate.
Solution:
# include <stdio.h>
main ()
{
int year, period;
float amount, inrate, value;
printf(“Enter amount, interest rate and period \n\n”);
scanf(“%f %f %d”, &amount, &inrate, &period);
printf(“\n”);
year = 1;
while ( year < = PERIOD)
{
value = amount + inrate * amount;
printf(“%2d Rs.%8.2f \n”, year, value);
amount = value;
year = year + 1;
}
}
Output:
Enter amount, interest rate and period:
10000 0.14 5
1 Rs. 11400.00
2 Rs. 12996.00
3 Rs. 14815.44
4 Rs. 16889.60
5 Rs. 19254.15
8. Write a C program to calculate the average of a set of N numbers:
Solution:
# include <stdio.h>
# define N 10
main ()
{
int count;
float sum, average, number;
sum = 0;
count = 0;
while (count < N)
{
scanf(“ %f ”, &number);
sum = sum + number;
count = count + 1;
}
average = sum / N;
printf(“N=%d Sum = %f ”, N, sum);
printf(“ Average = %f ”, average);
}

9. Write a C program to convert the given temperature in Fahrenheit to Celsius


using the following conversion formula
F−32
C=
1.8
Solution:
# include <stdio.h>
# define F_LOW 0
# define F_MAX 250
# define STEP 25
main ()
{
typedef float REAL;
REAL fahrenheit, celsius;
fahrenheit = F_LOW;
printf(“Fahrenheit Celsius\n\n”);
while(fahrenheit< = F_MAX)
{
celsius = ( fahrenheit – 32.0) / 1.8;
printf(“%5.1f %7.2f\n”, fahrenheit, celsius);
fahrenheit = fahrenheit + STEP;
}
}
Output:
Fahrenheit Celsius
0.0 – 17.78
25.0 – 3.89
50.0 10.00
75.0 23.89
⋮ ⋮
⋮ ⋮
250.0 121.11

10. Write a C program to convert a given number of days into months and days.
Solution:
# include <stdio.h>
main()
{
int months, days;
printf(“Enter days\n”);
scanf(“%d”, &days);
months = days / 30;
days = days%30;
printf(“Months = %d Days = %d”, months, days);
}
Output:
Enter days
265
Months = 8 Days = 25

11. Write a C program to sum the value using a cost.


Solution:
#include <stdio.h>
main()
{
float sum;
int n;
sum = 0;
for (n = 1; n < = 10; + + n)
{
sum = sum + 1 / (float) n;
printf(“%2d %6.4f \n”, n, sum);
}
}
Output:
1 1.0000
2 1.5000
3 1.8333
4 2.0833
⋮ ⋮
⋮ ⋮
10 2.9290
12. A computer manufacturing company has the following monthly
compensation policy to their sales – persons:
Minimum base salary : 1500.00
Bonus for every computer sold : 200.00
Commission on the total monthly sales : 2 percent.
Since the prices of computers are changing, the sales price of each computer is
fixed at the beginning of every month. A program to compute a sales – person’s
gross salary.
Solution:
The gross salary is given by the equation:
Gross Salary = base salary + (quantity * bonus rate) + (quantity * price) *
commission
#include <stdio.h>
# define BASE_SALARY 1500.00
# define BONUS_RATE 200.00
# define COMMISSION 0.02
main()
{
int quantity;
floatgross_salary, price;
float bonus, commission;
printf(“Enter number sold and price \n”);
scanf(“%d %f ”, &quantity, &price);
bonus = BONUS_RATE *quantity;
commission = COMMISSION * quantity * price;
gross_salary = BASE_SALARY + bonus + commission;
printf(“\n”);
printf(“Bonus =%6.2f \n”, bonus);
printf(“Commission =%6.2f \n”, commission);
printf(“Gross Salary =%6.2f \n”, gross_salary);
}
Output:
Enter number sold and price
5 20450.00
Bonus = 1000.00
Commission= 2045.00
Gross Salary= 4545.00

13. Write a C program to solve the quadratic equation.


Solution:
A quadratic equation has two roots:
−b+ √ (b2−4 ac )
root 1=
2a
−b−√ (b 2−4 ac)
root 2=
2a
# include <stdio.h>
# include <math.h>
main()
{
float a, b, c, discriminant, root1, root2;
printf(“Enter values of a, b and c \n”);
scanf(“%f %f %f ”, &a, &b, &c);
discriminant = b*b – 4*a*c;
if (discriminant < 0)
printf(“\n\n ROOTS ARE IMAGINAR \n”);
else
{
root1= (– b + sqrt (discriminant)) / (2.0*a);
root1= (– b – sqrt (discriminant)) / (2.0*a);
printf(“\n\n Root1 = %5.2f \n\n Root2 = %5.2f \n”, root1, root2);
}
}
MANAGING INPUT AND OUTPUT OPERATIONS
Reading a character or single character input:
Single character can be entered into 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.
In general terms, a reference to the getchar function is written as
variable _ name = getchar();
where variable _ name is a valid C name that has been declared as char type.
For example:
char name;
name = getchar();
Write a C program to show the use of getchar function.
Solution:
# include <stdio.h>
main()
{
char answer;
printf(“Would you like to know my name? \n”);
printf(“Type Y for YES and N for NO:”);
answer = getchar();
if(answer = = ‘Y’ || answer = = ‘y’)
printf(“\n\n My name is BUSY BEE \n”);
else
printf(“\n\n You are good for nothing \n”);
}
The getchar function may be called successively to read the characters
contained in a line of text.
For example:
……….
……….
char character;
character = ‘ ’;
while (character != ‘\n’)
{
Character = getchar();
}
………..
………..
The following functions are useful to identify what type of character we
typed from the keyboard.
Functions Test
isalnum(c) is c an alphanumeric character?
isalpha(c) isc an alphabetic character?
isdigit(c) is c a digit?
islower(c) is c a lower case letter?
isprint(c) is c a printable character?
ispunct(c) is c a punctuation mark?
isspace(c) is c a white space character?
isupper(c) is c an upper letter?
These character functions are contained in the file ctype.h and therefore the
statement
# include <ctype.h>
must be included in the program.
Example:
Write a C program to test the character type
Solution:
#include <stdio.h>
#include <ctype.h>
{
char character;
printf (“Press any key \n”);
character = getchar( );
if( is alpha (character) > 0)
printf (“The character is a letter”);
else
if( is digit(character) > 0)
printf(“The character is a digit”);
else
printf(“The character is not alphanumeric”);
}
Output:
Press any key
h
The character is a letter
Press any key
8
The character is a digit
Press any key

The character is not alphanumeric.
Writing a character or Single character output – The putchar function:
Single character can be displayed ( ie) written out of the computer) using
C library function putchar. This function is complementary to the character
input function of the standard C language I/O library. It transmits a single
character.
The general form of the Syntax is:
putchar (Variable_name);
wherevariable_name is a type char variable containing a character.
Example:
1. answer = ‘Y’;
putchar (answer);
will display the character Y on the screen.
2. putchar (‘\n’);
would cause the cursor on the screen to move to the beginning of the next line.
The following program uses three new functions islower, toupper and
tolower.
The function islower is a conditional function and takes the value TRUE if the
argument is a lower case alphabet; otherwise takes the value FALSE. The
function toupper converts the lower case argument into an upper case alphabet
while the function tolower does the reverse.
Program:
#include <stdio.h>
#include <ctype.h>
main ( )
{
char alphabet;
printf (“Enter an alphabet”);
putchar (‘\n’);
alphabet = getchar( );
if (islower(alphabet));
putchar(toupper (alphabet));
else
putchar(tolower (alphabet));
}
Output:
Enter an alphabet
a
A
Enter an alphabet
Q
q
FORMATTED INPUT:
Input data can be entered into the computer from a standard input device
by means of the C library function scanf. This function can be used to enter any
combination of numerical values, single characters and strings.
scanf(control string, arg1, arg2, …,arg n);
where 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 control string comprises individual groups of characters, with one
character group for each input data item. Each character group must begin with
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.
The more frequently used conversion characters are listed below:
Conversio Meaning
n
character
c Data item is a single character
d Data item is a decimal integer
e Data item is a floating point value
f Data item is a floating point value
g 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 a white space
character (the null character ¿ will automatically be
added at the end)
u Data item is an unsigned decimal integer
x Data item is a hexadecimal integer

The arguments are written as variables or arrays, whose types match the
corresponding character groups in the control string. Each variable name must
be preceded by an ampersand (&). However array names should not begin with
an ampersand.
Inputting Integer numbers:
The field specification for reading an integer number is: %wd
The percent sign (%) indicates that a conversion specification follows. w is an
integer number that specifies the field width of the number to be read.
Example:
1. scanf(“%2d %5d”, &num1, &num2);
Suppose the input is 50 31426.
The value 50 is assigned to num1 and 31426 to num2.
Suppose the input is 31426 50
The variable num1 will be assigned 31 (because of %2d) and num2 will be
assigned 426 (i.e. the unread part of 31426). The value 50 that is unread will
be assigned to the first variable in the next scanf call. This kind of errors may
be eliminated if we use the field specifications without the field width
specification.
i.e. The statement scanf(“%d%d”, &num1, &num2); will read the data
31426 50
correctly and assign 31426 to num1 and 50 to num2.
2. An input field may be skipped by specifying * in the place of field width.
The statement
scanf(“%d %*d %d”, &a, &b);
will assign the data
123 456 789
as follows
123 to a
456 skipped (because of *)
789 to b
3. We discuss the various input formatting options for reading integers in the
following program.
# include <stdio.h>
main()
{
int a, b, c, x, y, z;
int p, q, r;
printf(“Enter three integer numbers \n”);
scanf(“%d %*d %d”, &a, &b, &c);
printf(“%d %d %d \n\n”, a, b, c);
printf(“Enter two4 – digit number \n”);
scanf(“%2d %4d”, &x, &y);
printf(“%d %d \n\n”, x, y);
printf(“Enter two numbers \n”);
scanf(“%d %d”, &a, &x);
printf(“%d %d \n\n”, a, x);
printf(“Enter a nine digit number \n”);
scanf(“%3d %4d %3d”, &p, &q, &r);
printf(“%d %d %d \n\n”, p, q, r);
printf(“Enter two three digit numbers \n”);
scanf(“%d %d”, &x, &y);
printf(“%d %d”, x, y);
}
Output:
Enter three integer numbers
1 2 3
1 3 – 3577
Enter two 4 – digit numbers
6789 4321
67 89
Enter two integers
44 66
4321 44
Enter a nine digit number
123456789
66 1234 567
Enter two three digit numbers
123 456
89 123
Inputting Real numbers:
The field width of real numbers is not to be specified and therefore scanf
reads real numbers using the simple specification %f for both the notations
namely decimal point notation and exponential notation.
Example:
The statement
scanf(“%f %f %f”, &x, &y, &z);
with the input data
475.89 43.21E–1 678
will assign the value 475.89 to x, 4.321 to y and 678.0 to z.
The following example reading of real numbers (in both decimal point and
exponential notation):
# include <stdio.h>
main()
{
float x, y;
double p, q;
printf (“values of x and y \n”);
scanf (“%f %e”, &x, &y);
printf (x = %f \n y = %f \n\n”, x, y);
printf (“values of p and q \n”);
scanf (“%lf %lf ”, &p, &q);
printf (“\n p = % lf \n q = %e”, p, q);
printf (“\n\n p = %.12lf \n p = %.12e”, p, q);
}
Output:
Values of x and y:
12.3456 17.5e–2
x = 12.345600
y = 0.175000
Values of p and q:
4.142857142857 18.5678901234567890
p = 4.142857142857
q = 1.8567890123456e + 001
If the number to be read is of double type then the specification should be %lf
instead of %f. A number may be skipped using %*f specification.
Inputting Character Strings:
We know already how a single character can be read from the terminal
using the getchar function. The same can be achieved using the scanf function
also. In addition, a scanf function can input strings containing more than one
character.
Following are the specifications for reading character strings:
%ws or %wc.
When we use %wc for reading a string, the system will wait until the w th
character is keyed in. The specification %s terminates reading at the encounter
of a blank space.
Example:
1. #include<stdio.h>
main()
{
char item[20];
int part no;
float cost;
…………….
scanf (“%s %d %f ”, item, &part no, &cost);
……………..
}
The first character group %s indicates that the first argument (item)
represents a string. The second character group %d indicates the second
argument (&part no) represents a decimal integer value and the third character
group %f indicates that the third argument (&cost) represents a floating – point
value. Here notice that the numerical variables part no and cost are preceded by
ampersands within the scanf function. An ampersand does not precede item
since item is an array name.
2. #include <stdio.h>
main()
{
int i;
float x;
char c;
…………
………….
scanf(“%3d %5f %c”, &i, &x, &c);
If the data items are entered as
10 256.875 T
When the program is executed then 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.
3. #include<stdio.h>
main()
{
short ix, iy;
long lx, ly;
double dx, dy;
………………
scanf(“%hd %ld %lf ”, &ix, &lx, &dx);
………………
scanf(“%3ho %7lx %15le”, &iy, &ly, &dy);
……………….
}

The control string in the first scanf indicates that the first data item will
be assigned to a short decimal integer variable, the second will be assigned to a
long decimal integer variable and the third will be assigned to a double –
precision variable.
The control string in the second scanf indicates that the first data item
will have a maximum field width of three characters and it will be assigned to a
short octal integer variable, the second data item will have a maximum field
width of seven characters and it will be assigned to a long hexadecimal integer
variable and the third data item will have a maximum field width of 15
characters and it will be assigned to a double – precision variable.
FORMATTED OUTPUT:
Output data can be written from the computer onto a standard output
device using the library function printf. This function can be used to output any
combination of numerical values, single characters and strings. Hence the printf
function moves data from the computer’s memory to the standard output device.
In general terms, the printf function is written as printf( control string, arg1,
arg2, …. argn);
Where control string refers to a string that contains formatting information and
arg1, arg2,….,argn are arguments that represent the individual output data
items. The arguments can be written as constants, single variable or array names
or more complex expressions.
The arguments in a printf function do not represent memory addresses and
therefore they are not preceded by ampersands.
The control string is composed of individual groups of characters, with
one character group for each output data item. Each character group must begin
with a percent sign (%). In its simplest form, an individual character group will
consist of the percent sign followed by a conversion character indicating the
type of the corresponding data item.
Output of Integer Numbers:
The format specification for printing an integer number is %wd
where w specifies the minimum field width for the output. If a number is greater
than the specified field width, it will be printed in full. The number is written
right – justified in the given field width. Leading blanks will appear as
necessary.
Examples:
Format Output
9 8 7 6
printf (“%d”, 9876)

9 8 7 6
printf (“%6d”, 9876)

9 8 7 6
printf (“%2d”, 9876)

9 8 7 6

printf (“% –6d”, 9876)


Printing to left justified by placing a
minus directly after the % character.

0 0 9 8 7 6
printf (“%06d”, 9876)

Long integers may be printed by specifying ld in the place of d in the format


specification.
The following program illustrates the various output of integer numbers.
#include<stdio.h>
void main()
{
int m = 12345;
long n = 987654;
printf (“%d \n”, m);
printf (“%10d \n”, m);
printf (“%010d \n”, m);
printf (“% –10d \n”, m);
printf (“%10ld \n”, n);
printf (“%10ld \n”, –n);
}
Output:
12345
12345
0000012345
12345
987654
–987654
Output of Real Numbers:
The output of a real number may be displayed in decimal notation using the
following format specification %w.pf
Where w indicates the minimum number of positions that are to be used for the
display of the value and the integer p indicates the number of digits to be
displayed after the decimal point (precision).
Example:The following examples illustrate the output of the number y =
98.7654 under different format specifications:
Format Output
9 8 . 7 6 5 4
printf (“%7.4f”, y)

9 8 . 7 7
printf (“%7.2f”, y)
z
9 8 . 7 7
printf (“% –7.2f”, y)
z
9 8 . 7 6 5 4
printf (“% f”, y)
z
9 . 8 8 e + 0 1
printf (“%10.2e”, y) Z

– 9 . 8 7 6 5 e + 0 1
printf (“%11.4e”, –y)
z
9 . 8 8 e + 0 1
printf (“% –10.2e”, y) Z

printf (“%e”, y) 9 . 8 7 6 5 4 0 e + 0 1
z
Some system support a special field specification character that lets the user
defined field size at run – time.
This takes the following form: printf(“%*.*f”, width, precision, number);
In this case, both the field width and the precision are given as arguments which
will supply the values for w and p.
For example, printf (“%*.*f ”, 7, 2, number);is equivalent to printf (“%7.2f ”,
number);
The advantage of this format is that the values for wdth and precision
may be supplied at run – time, thus making the format a dynamic one.
For example, the above statement can be used as follows:
int width = 7;
int precision = 2;
………..
………..
printf (“%*.*f ”, width, precision, number);
The following example illustrates the various output of a real number:
# include <stdio.h>
void main()
{
floaty = 98.7654;
printf(“%7.4f \n”, y);
printf(“%f \n”, y);
printf(“%7.2f \n”, y);
printf(“% –7.2f \n”, y);
printf(“% 07.2f \n”, y);
printf(“% *.*f \n”, 7, 2, y);
printf(“\n”);
printf(“% 10.2e \n”, y);
printf(“% 12.4e \n”, –y);
printf(“% –10.2e \n”, y);
printf(“% e \n”, y);
}
Output:
98.7654
98.765404
98.77
98.77
0098.77
98.77
9.88e+001
–9.8765e+001
9.88e+001
9.876540e+001
Printing of a Single Character:
A single character can be displayed in a desire position using the format%wc
The character will be displayed right – justified in the field of w columns. We
can make the display left – justified by placing a minus sign before the integer
w. The default value for w is 1.
Printing of Strings:
The format specification for outputting strings is similar to that of real numbers.
It is of the form %w.ps
Where w specifies the field width for display and p instructs that only the first p
characters of the string are to be displayed. This display is right – justified.
The following examples show the effect of a variety of specifications in
printing a string “NEW DELHI 110 001”. Containing 16 characters (including
blanks).
Specification Output
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
%s
N E W D E L H I 1 1 0 0 0 1

%20s N E W D E L H I 1 1 0 0 0 1

%20.10s N E W D E L H I

%.5s N E W D

% –20.10s N E W D E L H I

%5s N E W D E L H I 1 1 0 0 0 1

Commonly used printf format codes are given in table below:


Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in exponent form
%f Print a floating point value without exponent
%g Print a floating point value either e–type or f–type
depending on value.
%i Print a signed decimal integer
%o Print an octal integer, without leading zero
%s Print a string
%u Print an unsigned decimal integer
%x Print a hexadecimal integer, without leading ox

The following letters may be used as prefix for certain conversion characters.
h for short integers
l for long integers or double
L for long double

Output Format Flags:


Flag Meaning
– Output is left – justified with the field. Remaining
field will be blank.
+ + or – will precede the signed numeric item.
o Causes leading zeroes to appear.
# (with o or Causes octal and hex items to be preceded by o and
x) ox respectively.
# (with e, f or Causes a decimal point to be present in all floating
g) point numbers, even if it is whole number. Also
prevents the truncation of trailing zeros in g–type
conversion.

All mathematical functions are defined in the header file math.h. In order
to use of these functions in a C programs, the appropriate header files must be
included in the beginning of the program using the # include preprocessor
directive.

Function Action (returns)


acos() the arc cosine of argument
asin() the arc sine of argument
atan() the arc tangent of argument
aceil the smallest integer
cos() the cosine of argument
cosh() the hyperbolic cosine of argument
exp() the natural logarithm e raised to the argument power.
fabs() the absolute values of number
floor() the largest integer
log() the natural logarithm
log10() the base 10 logarithm
pow() the base rasied to the expression power
sin() the sine of argument
sinh() the hyperbolic sine of argument
sqrt() the square root of argument
tan() the tangent of argument
tanh() the hyperbolic tangent of argument
1. Write a C program to convert temperature in centigrade to Fahrenheit and
vice – versa.
Soltion:
9
We know that F= 5 ∗C+ 32 or F=1.8∗C+32

where F denotes Fahrenheit and C denotes centigrade.


# include <stdio.h>
void main()
{
float c, f, ic, fi;
printf(“Enter temperature in centigrade \n”);
scanf(“%f ”, &c);
printf(“%5.1f \n”, c);
f = 1.8 * c + 32;
printf(“Fahrenheit equivalent to: %5.1f \n”, f);
printf(“\n Enter temperature in Fahrenheit \n”);
scanf(“%f ”, &fi);
printf(“%5.1f \n”, fi);
ic = (fi – 32)/1.8;
printf(“Centigrade equivalent is: %5.1f \n”, ic);
}

2. Program to find simple interest and compound interest.


Solution:
Simple interest (si) = PNR / 100,
Compound interest (ci) = P(1 + r / 100)n – P,
Where P denotes principle, N denotes the number of years and R denotes the
interest rate.
#include <stdio.h>
#include <math.h>
void main()
{
float p, r, t, si, ci, amount;
int n;
printf(“Enter principle, rate, time and compounding per year \n”);
scanf(“%f %f %f %d”, &p, &r, &t, &n);
printf(“%7.2f %7.2f %7.2f %5d \n\n”, p, r, t, n);
si = (p*t*r)/100;
printf(“simple interest = %7.2f \n”, si);
amount = p * pow((double)(1+r/(n*100)), (double(n*t));
ci = amount – p;
printf(“compound interest = %7.2f \n”, ci);
}
3. Write a C program: The reliability of an electronic component is given by
reliability ( r)=e−λt

where λ is the component failure rate per hour and t is the time of operation in
hours. A graph is required to determine the reliability at various operating
times, from 0 to 3000 hours. The failure rate λ is 0.001.
# include <stdio.h>
# include <math.h>
# define LAMDA 0.001
void main()
{
double t;
float r;
int i, R;
for (i = 1; i <= 27; ++i)
{
Printf(“– –”);
}
Printf(“\n”);
for (t = 0; t < = 3000; t + = 150)
{
r = exp (–LAMDA * t);
R = (int)(50*r+0.5);
Printf(“|”);
for(i=1; i<=R; ++i)
{
printf(“*”);
}
printf(“# \n”);
}
for(i=1; i<3; ++i)
{
Printf(“| \n”);
}
}
Output:
--------------------------------------------
|********************************#
| * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *#
| ****************************** * #
| …………………………………………
| ……………………………………..
| …………………………………..
| ………………………………..
| ……………………………..
| ………………………….
| ……………………
| ………………
| …………..
|***#
|**#
|*#

4. Write a C program for the given problem below:


Problem:
The ABC electric company manufactures four consumer products. Their
inventory position on a particular day is given below:
Code Quantity Rate (Rs)
F105 275 575.00
H220 107 99.95
I109 321 215.50
M315 89 725.00
It is required to prepare the inventory report table in the following format:
INVENTORY REPORT
Code Quantity Rate Value
--- --- --- ---
--- --- --- ---
--- --- --- ---
--- --- --- ---
Total Value: ---

The value of each item is given by the product of quantity and rate.
Solution:
# include <stdio.h>
# define ITEMS 4
void main()
{
int i, quantity[5];
float rate[5], value, total – value;
char code [5][5];
i = 1;
while (i<= ITEMS)
{
printf(“Enter code, quantity and rate:”);
scanf(“%s %d %f”, code[i], &quantity[i], &rate[i]);
i++;
}
printf(“\n\n”);
printf(“ INVENTORY REPORT \n”);
printf(“------------------------------------------------------------------------------\
n”);
printf(“ Code Quantity Rate Value
\n”);
printf(“------------------------------------------------------------------------------\
n”);
total–value=0;
i=1;
while(i<= ITEMS)
{
value = quantity [i] * rate [i];
printf(“%5s %10d %10.2f %e \n”, code[i], quantity[i], rate[i],
value);
total – value + = value;
i++;
}
printf(“------------------------------------------------------------------------------\
n”);
printf(“ Total Value = % e \n”, total–value);
printf(“------------------------------------------------------------------------------\
n”);
}
Output:
Enter code, quantity and rate: F105 275 575.00
Enter code, quantity and rate: H220 107 99.95
Enter code, quantity and rate: I019 321 215.50
Enter code, quantity and rate: M315 89 725.00
INVENTORY REPORT
Code Quantity Rate Value
F105 275 575.00 1.581250e+005
H220 107 99.95 1.069465e+004
I109 321 215.50 6.917550e+004
M315 89 725.00 6.452500e+004
Total Value = 3.025202e+005

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