C Programming
C Programming
C- PROGRAMMING
MODULE I
HISTORY OF C
1960 ALGOL International group
Fig 1.1
IMPORTANCE OF C
It is a structured, high level, machine independent
language.
3
CONSTANTS
Constants
Numeric Character
constants constants
Fig 1.2
Integer constants
An integer constant refers to a sequence of digits. There are
three types of integer constants namely decimal integer, octal integer,
hexadecimal integer.
Decimal integer consists of a set of digits, 0 through 9 preceded by an
optional + or – sign. Embedded zeros, commas, non-digit characters
are not allowed. Eg: 123, -321, +78 etc.
Any combination of numbers from the set 0 through 7 with a leading
zero is called octal integers. Eg: 034, 0986 etc.
A sequence of digits preceded by 0x or 0X is considered as
hexadecimal integer. They may include alphabets from A through F
or from a through f. The letters A through F represents the numbers
10 through 15. Eg: 0X2, ox9F, 0Xabcd etc.
Real constants
5
String constants
A string constant is a sequence of characters enclosed within
double quotes. The characters may be letters, numbers, special
characters and white spaces. Eg: “Hello”, “1989”, “?..!” etc.
String constants do not have corresponding integer ASCII values but
character constants have corresponding ASCII values.
VARIABLES
Variable is a data name that may be used to store data values.
Variables may take different values at different times during the
execution of the program. Rules for the variables are:
DATA TYPES
C supports 3 classes of data types. They are:
a) Primary (fundamental) data types.
b) Derived data types.
c) User defined data types.
FUNDAMENTAL DATA TYPES
1. Character type (char)
A single character can be defined as character type and it is
stored in 8 bits (1 byte)
2. Integer type (int)
Integers are whole numbers with a range of values supported by
particular machine. These are further classified into short int,
int, long int. This is stored in 16 bits (2 bytes)
3. Floating point type (float)
Floating point numbers are stored in 32 bits with 6 digits of
precision. When the accuracy provided by the float is not
sufficient then double is used.
4. Double type (double)
A double data type uses 64 bits giving a precision of 14 digits.
Double type represents the same data type that float represent,
but with a greater precision. To extend precision we use long
double.
5. Void
The void type has no value. This is used to specify the type of
functions.
7
DECLARATION OF VARIABLES
All variables must be declared before they appear in executable
statements.
Syntax: data type variable-name;
SYMBOLIC CONSTANTS
We often use certain unique constants in a program. These
constants may appear repeatedly in a number of places in the
program. One example of such a constant is mathematical constant
pi=3.14. Such constants are assigned to a symbolic name.
Syntax: #define symbolic-name value of constant
Eg: #define PI 3.142
Symbolic names are also called as constant identifier. The following
rules are applied while defining symbolic constants:
No blank space is permitted between the sign ‘#’ and the word
‘define’.
Symbolic names are written in capital letters.
A blank space is required between the #define and symbolic
name and between the symbolic name and constant.
#define statement should not end with a semi column.
#define statements may appear anywhere in the program but
before it is used in the program.
9
ARITHMETIC OPERATORS
C provides all the basic arithmetic operators. They are listed in
table 1.2. The modulo division operation provides the reminder of an
integer division. The arithmetic operation can be further classified
into integer arithmetic, real arithmetic and mixed-mode arithmetic.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Table 1.2
RELATIONAL OPERATORS
The operators used to compare the relation between two
variables are called relational operators. The result will always be in
binary. The following are the relational operators used:
Operator Meaning
< Is less than
10
LOGICAL OPERATORS
In addition to relational operators C supports three logical
operators. The logical operators are used when we want to test more
than one condition. An example is a>b && x==10. Logical operators
combine two or more relational expressions and hence it is also called
compound relational operators.
Operator Meaning
&& Logical AND
ΙΙ Logical OR
! Logical NOT
Table 1.4
ASSIGNMENT OPERATORS
Assignment operators are used to assign the result of an
expression to a variable. In C the assignment operator is ‘=’. In
addition, C has a set of shorthand assignment operators. The
shorthand operators are very simple and easy to write. Some
shorthand operators and their corresponding single assignment
operators are given:
Statement with simple operator Shorthand operator
a = a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a %b a%=b
Table 1.5
11
CONDITIONAL OPERATORS
This operator is used to evaluate an expression and conditional
execution of a statement. This operator is also called as ternary
operator because it operates on three operands.
Syntax: Expr1? Expr2: Expr3
This operator works as follows: Expr1 is evaluated first. If it is true,
then the Expr2 is evaluated and becomes the value of expression. If
Exp1 is false, then Expr3 is evaluated and its value becomes the value
of expression.
Eg: a=10; b=15; x= (a>b)? a : b; this can be explained
using if else statement. if (a>b); x=a;
else x=b;
BITWISE OPERATORS
12
SPECIAL OPERATORS
C supports some special operators such as comma operator,
sizeof operator, pointer operators and member selection operators.
The comma operator
The comma operator can be used to link the related expressions
together. Comma-linked expressions are evaluated left to right and the
value of right-most expression is the value of combined expression.
Eg: sum=(x=10,y=5,x+y); this statement first assigns the value
10 to x and 5 to y and finally assigns 15 to sum.
The sizeof operator
The size of operator is a compile time operator. When it is used
with an operand, it returns the number of bytes the operand occupies.
The operand may be a variable, a constant or a data type. Eg:
m=sizeof (total);here if total is integer type, then it assigns a value 2
to m because the size of integer is 2 bytes.
13
WRITING A CHARACTER
Writing a single character can be done by using the function
putchar ().
Syntax: putchar(variable name);
Eg: char answer=’v’;
putchar (answer); A group of characters can be written
using putchar (). It displays all the characters except the new line
character which is at the end of string.
Syntax: puts (string);
FORMATTED INPUT
14
FORMATTED OUTPUT
Formatted output refers to an output data that has been arranged in
some format.
Syntax: printf(“control string”,arg1, arg2, ….argn);
Here control string consist of characters, data items of variables in
specified format and escape sequence characters such as \n, \t, \b etc.
arg1, arg2 are variable names whose values are to be printed in the
required format.
Eg: printf(“%d%f%c”,count, price, name);
15
APPENDIX I
C CHARACTER SET
Letters:
Uppercase A……….Z
Lowercase a………..z
Digits:
All decimal digits 0…..9
Special characters:
, comma & ampersand ; semicolon
. period ^ caret : colon
< opening angle bracket * asterisk - minus sign
(less than sign) + plus sign ‘ apostrophe
( left parenthesis / back slash \ slash
) right parenthesis Ι vertical bar ~ tilde
! exclamation mark _ underscore $ dollar sign
? question mark % percentage sign [ left bracket
16
APPENDIX II
TRIGRAPH CHARACTERS
Many non-English keywords do not support all the characters in
the above list. ANSI C introduces the concept of trigraph sequences to
provide a way to enter certain characters that are not available on
some keywords. Each trigraph sequences consists of three characters
(two question marks followed by another character) as shown in table.
Trigraph sequence Translation
??= # number sign
??( [ left bracket
??) ] right bracket
??< { left brace
??> } right brace
??! Ι vertical bar
??/
??- ~ tilde
ANSI C Trigraph Sequences
APPENDIX III
BACKSLASH CHARACTER CONSTANTS
Constant Meaning
‘\a’ Audible alert (bell)
17
APPENDIX IV
ASCII VALUES OF CHARACTERS
ASCII value ASCII value ASCII value ASCII value
character character character character
000 NUL 032 BLANK 064 @ 096 ←
001 SOH 033 ! 065 A 097 a
002 STX 034 “ 066 B 098 b
003 ETX 035 # 067 C 099 c
004 EOT 036 $ 068 D 100 d
005 ENQ 037 % 069 E 101 e
006 ACK 038 & 070 F 102 f
007 BEL 039 ‘ 071 G 103 g
008 BS 040 ( 072 H 104 h
009 HT 041 ) 073 I 105 i
010 LF 042 * 074 J 106 j
011 VT 043 + 075 K 107 k
012 FF 044 , 076 L 108 l
013 CR 045 _ 077 M 109 m
014 SO 046 . 078 N 110 n
015 SI 047 / 079 O 111 o
016 DLE 048 0 080 P 112 p
18
APPENDIX V
SUMMARY OF C OPERATORS
Operator Description Associativity Rank
() Function call Left to right 1
[] Array elements
reference
+ Unary plus Right to left 2
- Unary minus
++ Increment
-- Decrement
! Logical
negation
~ Ones
complement
* Pointer
reference
& Address
sizeof Size of an
19
object
(type) Type cast
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right shift
< Less than Left to right 6
<= Less than or
equal to
> Greater than
>= Greater than or
equal to
== Equality Left to right 7
!= Not equality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
Ι Bitwise OR Left to right 10
&& Logical AND Left to right 11
ΙΙ Logical OR Left to right 12
?: Conditional Right to left 13
expression
= Assignment Right to left 14
*=/=%= operators
+=-=&=
^=Ι=
<<=>>=
, Comma Left to right 15
operator
20
MODULE II
SIMPLE IF STATEMENT
The general form is:
If (test expression)
{
Statement block
}
Statement-x
The ‘statement block’ may be a single statement or a group of
statements. If the test expression is true, the statement block will be
executed; otherwise the statement block will be skipped and the
execution will jump to the statement-x. Remember, when the
condition is true both the statement-block and the statement-x are
executed in sequence. The flow chart is given:
Entry
Test expression
True
Statement-block
False
Statement-x
Next statement
Eg: ………………
…………
23
if (category==sports)
{
marks=marks + bonus marks
}
Printf (“%f”, marks);
………….
…………..
THE IF…….ELSE STATEMENT
The if…..else statement is an extension of the simple if
statement. The general form is
If (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement-x
If the test expression is true, then the true block statement(s),
immediately following the if statements are executed; otherwise, the
false-block statement(s) are executed. In either case, either true-block
or false-block will be executed, not both. Flow chart is given below:
24
Entry
Text expression
True False
Statement-x
Eg …………….
…………….
if (code==1)
boy = boy +1
else
girl = girl +1
……………….
……………….
NESTING OF IF……ELSE STATEMENT
When a series of decisions are involved, we may use more than
one if…..else statement in nested form as shown. If the condition 1 is
false, the statement 3 will be executed; otherwise it continues to
perform the second test. If the condition 2 is true, the statement 1 will
be evaluated; otherwise the statement 2 will be evaluated and then the
control is transferred to the statement-x.
if (test condition 1)
{
if (test condition 2)
{
statement 1;
}
else
25
{
statement 2;
}
}
else
{
statement 3;
}
statement-x;
Eg: …………..
……………
if (sex is female)
{
If (balance > 5000)
Bonus=.05*balance;
Else
Bonus=.02*balance;
}
Else
{
Bonus=.02*balance;
}
…………….
……………..
The flow chart is given below:
26
Entry
Test condition 1
True
Test condition 2
False
False True
Statement
Statement 32 Statement 1
Statement-x
Next statement
THE ELSE IF LADDER
There is another way of putting ifs together when multipath
decisions are involved. A multipath decision is a chain of ifs in which
the statement associated with each else is an if.
if (condition 1)
27
statement 1;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;
This construct is known as the else if ladder. The condition is
evaluated from the top downwards. As soon as a true condition is
found, the statement associated with it is executed and the control is
transferred to the statement x (skipping the rest of the ladder). When
all the n conditions become false, the final else containing the default
statement is executed. Consider an example;
………………
if (code==1)
color=”RED”;
else if (code==2)
color=”GREEN”;
else if (code==3)
color=”WHITE”;
else
color=”YELLOW”;
……………...
Entry
Cdtn 1
Cdtn 2
Stmnt 1
28
T F
T F
T F
T F
switch (expression)
{
case value 1:
block 1
break;
case value 2:
block 2
break;
……………….
……………….
default:
default block
break;
}
statement x;
The expression is an integer or characters. Value 1, value 2….are
constants or constant expressions and are known as case labels. Each
of these values should be unique within a switch statement. Block 1,
block 2…..are statement lists and may contain zero or more
statements.
When the switch is executed, the value of the expression is
successfully compared against the values value 1, value 2 …. If a case
is found whose value matches with the value of the expression, then
the block of statements that follow the case are executed. The break
statement at the end of each block signal the end of a particular case
and causes an exit from the switch,
statement transferring the control to the statement x following the
switch.
The default is an optional case. When present, it will be executed if
the value of the expression does not match with any of the case value.
If not present no action takes place if all matches fails and control
goes to the statement x. flow chart is given below:
30
Entry
Switch exp.
Expn=value 1
Block 1
Expn=value 2
Block 2
........………………..
(no match) default
Default block
……………..
Index=marks/10;
Switch (index)
{
Case 10:
Grade=”A plus”;
Case 9:
Grade=”A”;
Case 8:
Grade=”B plus”;
………………..
THE ? : OPERATOR
The C language has an unusual operator, useful for making two-
way decisions. This operator is combination of ? and :, and takes three
operands. This operator is popularly known as conditional operator.
The general form is:
31
THE DO STATEMENT