Module 2
Module 2
C language Preliminaries
Introduction to C Language
Structure of a C program:
The basic structure of a C program is shown below
Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
{
Declaration Part
Executable Part
}
Subprogram section
Function 1
Function 2
.
.
.
Function n
The documentation section consists of a set of comment lines giving the name of the program,
the name author and other details which the programmer would like to use later. The link section
provides instructions to the compiler to link functions from the system library. The definition
section contains all symbolic constants. There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global declaration
section. Every C program must have one main() function section. This section contains two parts
declaration part and executable part. The declaration part declares all the variables used in the
executable part. There should be at least one statement in the executable part. These two parts
must appear between the opening and the closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function section is
logical end of the program. All statements in the declaration and executable parts end with a
semicolon. The subprogram section contains all the user-defined functions that are called in the
main function. The main function is very important compared to other sections.
Character Set
The characters that can be used to form words, numbers and expressions depend upon the
computer on which the program is run. The characters in C are grouped into the following
categories.
1. Letters
2. Digits
3. Special characters
4. White Spaces
Letters Digits
Uppercase A…Z All decimal digits 0…9
Lowercase a….z
Special characters
, comma & ampersand
. period ^ carat
; semicolon *asterisk
: colon -minus sign
? question mark + sign
‘ apostrophe < opening angle bracket
! exclamation mark (or less than sign)
| vertical bar > closing angle bracket
/ slash (or greater than sign)
\ backslash ( left parenthesis
~ tilde ) right parenthesis
_ underscore [ left bracket
$ dollar sign ] right bracket
% percent sign { left brace
# number sign } right brace
White Spaces
Blank Space
Horizontal tab
Carriage return
New line
Form feed
Identifiers:
In c language every word is classified into either keyword or identifier. All keywords have
fixed meanings and these meanings cannot be changed. These serve as basic building blocks for
program statements. All keywords must be written in lowercase. The list of all ANSI C
keywords are listed below
ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers refer to the names of variables, functions and arrays. These are user defined
names and consist of a sequence of letters and digits, with a letter as a first character. Both
uppercase and lowercase letters are permitted, although lowercase letters are commonly used.
The underscore character is also permitted in identifiers. It is usually used as a link between two
word in long identifiers.
Integer Constants:
An integer constant refers to a sequence of digits. There are three types of integers,
namely decimal, octal and hexadecimal. Decimal integers consist of a set of digits 0 through 9,
preceded by an optional – or + sign. Some examples of decimal integer constants are
123
-431
34567
+678
Spaces, commas, and non-digit characters are not permitted between digits. For example
15 750
20,000
Rs 1000
.95
-.71
+.5
A real number may also be expressed in exponential(or specific notation). For example the value
213.45 may be written as 2.1345e2 in exponential notation. e2 means multiply by 102. The
general form is
mantissa e exponent
Character Constants:
A character constant contains a single character enclosed within a pair of single quote
marks. Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
Note that the character constant ‘5’ is not the same as the number 5. The last constant is a blank
space. Character constants have integer values known as ASCII values. For Example, the
statement
printf (“%d”, ‘A’);
would print the number 65,the ASCII value of the letter a. Similarly, the statement
printf(“%c”, 65)
would give the output as letter ‘A’. It is also possible to perform arithmetic operations on
character constants.
Backslash Character Constants:
C supports some special backslash character constants that are used in output functions. For
example, the symbol ‘\n’ stands for new line character. The below table gives you a list of
backslash constants.
Variable names may consist of letters, digits, and the underscore(_) character, subject to the rules
given below:
1. The variables must always begin with a letter. Some systems permit underscore as the
first character.
2. ANSI standard recognizes a length of 31 characters. However, the length should not
be normally mare than eight characters. Since first eight characters are treated as
significant by many compilers.
3. Uppercase and lowercase are significant. That is ,the variable Rate is not the same as
rate or TOTAL.
4. The variable name should not be a keyword.
5. White space is not allowed.
Some examples are given below:
Abhi Value I_rate
Mumbai s1 ph_value
Rate sum1 distance
The examples given below are invalid:
345 (rate)
% 56 nd
Declaration of variables:
Identifiers which are used as variable names should be prefixed as integer or float
by the following declaration should appear at the beginning of a program before the variable
names are used.
type _name variable name……variable name;
The type_name is always a reserved word. The type_name available for variable names storing
numbers are int for integers and float for floating point numbers. Valid examples are given
below:
int n, height ,count ,digit;
float rate, average , y_coordinate,p1;
When a variable name is declared then a memory location is identified and given this name.
The following declarations of variables are invalid:
Float a ,b ,c ; (comma after float is not valid)
Char, int, float and double are all keywords and therefore their use is reserved. They may not be
used as names of variables. Char stands for “character” and int stands for “integer”. The
keywords short int, long int and unsigned int may be and usually are, shortened to just short,
long, and unsigned, respectively. Also, double and long float are equivalent, but double is the
keyword usually used.
Integer Types:
Integers are whole numbers with a range of values supported by a particular machine. Generally
integers occupy one word of storage. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767. A signed integer uses one bit for sign and 15 bits
for the magnitude of the number. Similarly, a 32 bit word length can store an integer ranging
from -2,147,483,648 to 2,147,483,647. C has three classes of integer storage, namely short int,
int, and long int in both unsigned and signed forms. For example, short int represents fairly small
integer.
Values and requires half the amount of storage as a regular int number uses. Unlike signed
integers, unsigned integers use all the bits for the magnitude of the number and are always
positive. Therefore, for a 16 bit machine, the range of unsigned integer numbers will be from 0 to
65,535. We declare long and unsigned integers to increase the range of values.
Scanf functions:-
The function scanf() is used to read data into variables from the standard input, namely a
keyboard. The general format is:
Scanf(format-string, var1,var2,………varn)
Where format-string gives information to the computer on the type of data to be stored in the list
of variables var1,var2……varn and in how many columns they will be found
For example, in the statement:
Scanf(“%d %d”, &p, &q);
The two variables in which numbers are used to be stored are p and q. The data to be stored are
integers. The integers will be separated by a blank in the data typed on the keyboard.
A sample data line may thus be:
456 18578
Observe that the symbol &(called ampersand) should precede each variable name. Ampersand is
used to indicate that the address of the variable name should be found to store a value in it. The
manner in which data is read by a scanf statement may be explained by assuming an arrow to be
positioned above the first data value. The arrow moves to the next data value after storing the
first data value in the storage location corresponding to the first variable name in the list. A blank
character should separate the data values. The scanf statement causes data to be read from one or
more lines till numbers are stored in all the specified variable [Link] that no blanks should be
left between characters in the format-string. The symbol & is very essential in front of the
variable name. If some of the variables in the list of variables in the list of variables in scanf are
of type integer and some are float, appropriate descriptions should be used in the format-string.
For example:
Scanf(“%d %f %e”, &a , &b, &c);
Specifies that an integer is to be stored in a, float is to be stored in b and a float written using the
exponent format in c. The appropriate sample data line is:
485 498.762 6.845e-12
Printf function:
The general format of an output function is
Printf(format-string, var1,var2…..varn);
Where format-string gives information on how many variables to expect, what type of
arguments they are , how many columns are to be reserved for displaying them and any
character string to be printed. The printf() function may sometimes display only a message and
not any variable value. In the following example:
printf(“Answers are given below”);
The format-string is:
Answers are given below
And there are no variables. This statement displays the format-string on the video display and
there are no variables. After displaying, the cursor on the screen will remain at the end of the
string. If we want it to move to the next line to display information on the next line, we should
have the format-string:
printf(“Answers are given below\n”);
In this string the symbol \n commands that the cursor should advance to the beginning of the
next line.
In the following example:
printf(“Answer x= %d \n”, x);
%d specifies how the value of x is to be displayed. It indicates the x is to be displayed as a
decimal integer. The variable x is of type int. %d is called the conversion specification and d the
conversion character . In the example:
printf(“a= %d, b=%f\n”, a, b);
the variable a is of type int and b of type float or double. % d specifies that a is to be displayed as
an integer and %f specifies that, b is to be displayed as a decimal fraction. In this example %d
and %f are conversion specifications and d, f are conversion characters. Example to indicate how
printf() displays answers.
/*Program illustrating printf()*/
# include<stdio.h>
main()
{
int a= 45, b= 67
float x=45.78 , y=34.90
printf(“Output:\n”);
printf(“1,2,3,4,5,6,7,,8,0\n”);
printf(“\n”);
printf(“%d, %d,,%f ,%f \n” , a,b,x,y);
printf(“\n”);
}
Output:
1234567890
45,67,45.78,34.90
Input:
-768 0362 abf6 3856 -26.68 2.8e-3 1.256e22 6.856
Output:
conversion specification begins with a % and ends with a conversion character. Between the %
and the conversion character there may be in order:
• A minus sign, which specifies left adjustment of the converted argument.
• A number that specifies the minimum field width. The converted argument will be
printed in a field at least this wide. If necessary it will be padded on the left or right, to
make up the field width.
• A period, which separates the field width from the precision.
• A number, the precision, that specifies the maximum number of characters to printed
from a string, or the number of digits after the decimal point of a floating point value, or
the minimum number of digits for an integer.
• An h if the integer is to be printed as a short, or l if as a long.
printf(“hello, world\7”);
printf(“hello, world\?”);
}
{
scanf(“%f”, &number);
sum=sum+number;
count=count+1;
}
average= sum/N;
printf(“N=%d Sum= %f”, N, sum);
printf(“Average=%f”, average);
}
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division produces the remainder of an
integer division.
Examples are:
a-b a+b
a*b a/b
a%b -a * b
Here a and b are variables and are known as operands. The modulo divison operator % cannot be
used on floating point data.
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;
The table below shows the algebraic expression and C language expression
Algebraic expression C expression
a x b-c a*b-c
(m + n) (x + y) (m + n) *(x + y)
(a b)/c a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y +c x/y + c
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the precious value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is attempted.
x=a*b-c;
y=b/c*a;
z=a-b/c+d;
The blank space around an operator is optional and adds only to improve readability. When these
statements are used in a program, the variables a ,b ,c and d must be defined before they are used
in the expressions.
Modes of expression:
There are three different modes of expression.
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed-mode Arithmetic
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic. This
mode of expression always yields an integer value. The largest integer value depends on the
machine, as pointed out earlier
Example:
If a and b are integers then for a=14 and b=4
We have the following results:
a - b=10
a + b = 18
a * b = 56
a / b=3
a %b=2
During integer division, if both the operands are of the same sign, the result is truncated towards
zero. If one of them is negative, the direction of truncation is implementation dependent. That
is, 6/7=0 and -6/-7=0
but -6/7 may be zero -1 (Machine dependent)
Similarly, during modulo division , the sign of the result is always the sign of the first
operand(the dividend). That is
-14 % 3 =-2
-14 % -3= -2
14 % -3=2
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation. Since floating point
values are rounded to the number of significant digits permissible, the final value is an
approximation of the correct result. If x, y, and z are floats, then we will have:
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z= -2.0/3.0= -0.666667
The operator % cannot be used with real operands.
Mixed- mode Arithmetic
When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then only the real operation is
performed and the result is always a real number.
Thus
15/10.0=1.5
where as
15/10=1
Arithmetic operators precedence:-
In a program the value of any expression is calculated by executing one arithmetic
operation at a time. The order in which the arithmetic operations are executed in an expression is
based on the rules of precedence of operators.
The precedence of operators is :
Unary (-) FIRST
Multiplication(*) SECOND
Division(/) and (%)
Addition(+) and Subtraction(-) LAST
For example, in the integer expression –a *b/c+d the unary- is done first, the result –a is
multiplied by b, the product is divided by c(integer division) and d is added to it. The answer is
thus:
-ab/c+d
All the expressions are evaluated from left to right. All the unary negations are done first. After
completing this the expression is scanned from left to right; now all *, / and % operations are
executed in the order of their appearance. Finally all the additions and subtractions are done
starting from the left of the expression..
For example, in the expression:
Z=a + b* c
Initially b*c is evaluated and then the resultant is added with a. Suppose if want to add a with b
first, then it should be enclosed with parenthesis , is shown below
Z = (a + b) * c
Use of parentheses:
Parentheses are used if the order of operations governed by the precedence rules are to
[Link] the expression with a single pair of parentheses the expression inside the
parentheses is evaluated FIRST. Within the parentheses the evaluation is governed by the
precedence rules.
For example, in the expression:
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+dk/m+k
After this the expression is evaluated from left to right using again the rules of precedence giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair is
evaluated first, the next innermost and so on till all parentheses are removed. After this the
operator precedence rules are used in evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
xy,np+j will be evaluated first.
In the next scan
Xy+z/np+j +x
Will be evaluated. In the final scan the expression evaluated would be:
(Xy+ z/np+j+x)/y +z
so on. These comparisons can be done with the help of relational operators. C supports six
relational operators in all. These operators and their meanings are shown below
Relational Operators
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and has the following form:
ae- 1 relational operator ae-2. ae-1 and ae-2 are arithmetic expressions, which may be simple
constants, variables or combination of them.
Given below are some examples of simple relational expressions and their values:
4.5<= 10 TRUE
4.5< 10 FALSE
-35>= 0 FALSE
10< 7+5 TRUE
a+b == c+d TRUE only if the sum of values of a and b is equal to the sum of values of c
and d.
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators
have a higher priority over relational operators. Relational expressions are used in decision
statements such as, if and while to decide the course of action of a running program.
Logical operators:
In addition to the relational operators . C has the following three logical operators.
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to test more than one condition and make
decisions.
Example:
a>b && x == 10
An expression of this kind which combines two or more relational expression is termed as a
logical expression or a compound relational expression. Like the simple relational expressions , a
logical expression also yields a value of one or zero, according to the truth table shown below.
The logical expression given above is true only if a>b is true and x==10 is true. If either (or
both) of them are false, the expression is false.
Truth Table
Op-1 op-2 Value of the expression
Op-1 && op-2 op-1 || op2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
If he gets less than 50 percent in Physics he should get 50 percent or more in Mathematics. He
should get atleast 40 percent in Physics.
If he gets less than 40 percent in Mathematics and 60 percent or more in Physics he is allowed to
reappear in an examination in Mathematics to qualify.
In all the other cases he is declared to have failed.
Bitwise 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. where the filename is the name
containing the required definitions or functions. At this point, the preprocessor inserts the entire
contents of the filename into the source code of the program. When the filename is included
within the double quotation marks, the search for the file is made first in the directory and then in
the standard directories.
Bitwise Operators
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One’s Complement
|| Logical OR
?: Conditional expression
= Assignment operators
*= /= %=
+= -= &=
^= |=
<<= >>=
, Comma operator
The associatively of operators:
The operators of the same precedence are evaluated either from left to right or from right to left
depending on the level. This is known as the associatively property of an operator.
The table below shows the associatively of the operators:
Operators Associativity
() [ ] → left to right
~ ! –(unary) left to right
++ -- size of(type)
&(address) left to right
*(pointer)
*/ %
<< >> left to right
<<= >>= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
=+ =- *= /= %= &= ^= |= <<= >>= right to left
,(comma operator) left to right