Você está na página 1de 33

1

C- PROGRAMMING

MODULE I

Topic:-Introduction to C: C fundamentals-The character set-


identifiers and keywords-Data types-constants-variables and arrays-
declarations-expressions-statements-symbolic constants-arithmetic
operators-Relational and logical operators-The conditional operators-
Library functions-Data input and output-get char-put char, scanf,
printf-gets and puts functions-interactive programming.
2

HISTORY OF C
1960 ALGOL International group

1967 BCPL Martin Richards

1970 B Ken Thomson

1972 Traditional C Dennis Ritchie

1978 K&RC Kernighan & Ritchie

1989 ANSI C ANSI Committee

1990 ANSI/ISO C ISO Committee

1999 C99 Standardization


Committee

Fig 1.1

IMPORTANCE OF C
 It is a structured, high level, machine independent
language.
3

 It allows software developers to develop programs without


worrying about the hardware platforms where they are
implemented.
 The C compiler combines the capabilities of an assembly
language with the features of high level language and
therefore it is well suited for writing both system software
and business packages.
 Programs written in C are efficient and fast. This is due to
its variety of data types and powerful operators.
 There are only 32 keywords in ANSI C and its strength
lies in its built-in functions.
 C is highly portable.
 C language is well suited for structured programming, thus
requiring the user to think of a problem in terms of
function modules or blocks. A proper collection of these
modules make a complete program. This modular structure
makes program debugging, testing and maintenance easier.
 It has the ability to extend itself. A C program is basically
a collection of functions that are supported y the C library.
We can continuously add our own functions to C library.

KEYWORDS AND IDENTIFIERS


Every C word can be classified into keywords and identifiers.
Keywords have fixed meaning and that cannot be changed. Keyword
serves as the building blocks for program statements. All the
keywords must write in lower case letters.
Eg: do, while, if, break etc.
Identifiers are the names of variables, functions and arrays. These are
user defined names and consist of a sequence of letters and digits with
the letter as a first character. Both upper and lower case letters are
permitted. Underscore characters are also permitted.
4

CONSTANTS

Constants

Numeric Character
constants constants

Integer Real constants Single character String


constants 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

Some qualities like heights, temperature etc. are represented by


numbers containing fractional parts. Such numbers are called real (or
floating point) constants. Eg. .95, -.71 etc.

Single character constants


It contains only single character enclosed within a pair of single
quote marks. Eg: ‘5’, ‘X’ etc.
Character constants have integer values known as ASCII values. Eg:
printf (“%d”, ’a’); would print the value 97 and also printf (“%c”,
‘97’) would print the letter ‘a’.

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.

Backslash character constants


C supports some special backslash character constants that are
used in output functions. The symbol ‘\n’ stands for new line. Eg:
‘\0’, ‘\t’ etc.

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:

 First character must be a letter.


 It should contain only letters, digits and underscores.
6

 Characters up to 31 are identified by the compiler but in most


cases up to 8 characters are significant.
 It should not be a keyword.
 It must not contain white spaces.

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

Type Size in bytes Range of values


Char 1 -128 to +127
Int 2 -32768 to +32767
Float 4 3.4E-38 to 1.7E+308
Double 8 1.7E-308 to 1.7E+308
Table 1.1
DERIVED DATA TYPE
These include arrays, functions, structures and pointers.
USER DEFINED DATA TYPES
C supports the feature known as type definition which allows
the user to define an identifier that would represent an existing data
type. The user defined data type identifier can later be used to declare
variables. Its general form is:
typedef type identifier;
Where type refers to an existing data type and “identifier” refers to the
new name given to the data type.
Eg: typedef int units; Here the unit symbolizes int and it can be
later used to declare variables as follows: units
batch 1, batch 2;
The main advantage of typedef is that we can create meaningful data
type names for increasing the readability of the program.

DECLARATION OF VARIABLES
All variables must be declared before they appear in executable
statements.
Syntax: data type variable-name;

ASSIGNING VALUES TO THE VARIABLES


8

Values can be assigned to the variables using the assignment


operator ‘=’ as follows:
Syntax: variable-name=a constant;
It is also possible to assign the values to the variable during the
declaration as follows:
Syntax: data type variable-name=a constant;
The process of giving initial values to the variable is known as
initialization. Remember that external and static variables are
initialized to zero by default. Automatic variables that are not
initialized explicitly will contain garbage.

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

OPERATORS AND EXPRESSIONS


C supports several types of operators. They can be classified
into a number of categories. They include:
1.Arithmetic operators
2.Relational operators
3.Logical operators
4.Assignment operators
5.Increment and decrement operators
6.Conditional operators
7.Bitwise operators
8.Special operators

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

<= Is less than or equal to


> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Table 1.3

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

INCREMENT AND DECREMENT OPERATORS


These operators operate only on one operand. So it is also called
unary operator.
Operator Meaning
++ Add 1 to operand
-- Subtract 1 from the operand
Table 1.6
These operators can be used before or after the variable name.

 If placed before the variable name, then it is known as pre-


increment/pre-decrement operator. Eg: sum=++i; [first ‘i’ is
incremented by 1 and then it is assigned to sum]
 If placed after the variable name, then it is known as post-
increment/post-decrement operator. Eg: sum=i++; [first i is
assigned to sum then value of i is incremented by 1.

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

C has 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 to right or left. Bitwise
operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
I Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ One’s complement
Table 1.7

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

INPUT AND OUTPUT OPERATORS


READING A CHARACTER
A single character can be read by using the function getchar ().
Syntax: variable name=getchar ();
Variable name is any valid C name that has been declared as char
type. Here the computer waits until a key is pressed and then assigns
the value of this character to the variable name.
Eg: char name;
name=getchar ();
A group of characters can be read using the function gets(). It reads
the characters until the enter key is pressed.
Syntax: gets(string);
here string is a group of characters of type char.

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 input refers to an input data that has been arranged in


some format.
Syntax: scanf(“control string”, arg1, arg2,……argn);
Here control string specifies the field format in which the data is to be
entered and the arguments arg1, arg2 …argn specify the address of
the locations where data is to be stored. Control string contains field
specification of input data and it may include,
1. Field specifications, consisting of the conversion character (%)
followed by a data type character and an optional number
specifying the field width.
2. Blanks, tabs or newlines.
Eg: int count;
float no;
char name;
scanf (“%d%f%c”, &count, &no, &name);

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

“ quotation mark # number sign { left brace


] right bracket } right brace
White spaces:
Blank space Horizontal tab New line
Carriage return Form feed

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

‘\b’ Back space


‘\f’ Form feed
‘\n’ New line
‘\t’ Horizontal tab
‘\v’ Vertical tab
‘\” Single quote
‘\\’ Backslash
‘\”’ Double quote
‘\r’ Carriage return
‘\?’ Question mark
‘\0’ Null

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

017 DC1 049 1 081 Q 113 q


018 DC2 050 2 082 R 114 r
019 DC3 051 3 083 S 115 s
020 DC4 052 4 084 T 116 t
021 NAK 053 5 085 U 117 u
022 SYN 054 6 086 V 118 v
023 ETB 055 7 087 W 119 w
024 CAN 056 8 088 X 120 x
025 EM 057 9 089 Y 121 y
026 SUB 058 : 090 Z 122 z
027 ESC 059 ; 091 [ 123 {
028 FS 060 < 092 \ 124 Ι
029 GS 061 = 093 ] 125 }
030 RS 062 > 094 ↑ 126 ~
031 US 063 ? 095 - 127 DEL

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

Topic: Control statements: while-do while-for nested loops-if else


switch break-continue-The comma operator-go to statement-
Functions-a brief overview-defining a function-accessing a function-
passing arguments to a function-specifying argument-data types-
function prototypes-Recursion.
21

DECISION MAKING AND


BRANCHING
C language possesses some decision making capabilities by
supporting the following statements:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
These statements are popularly known as decision-making statements.
Since statements control the flow of execution, they are also known as
control statements.

DECISION MAKING WITH IF STATEMENT


The if state is a powerful decision making statement and is used
to control the execution of statements. It is basically a two way
decision statement and is used in conjunction with an expression.
Syntax: if (test expression);
It allows the computer to evaluate the expression first and the
depending on whether the value of the expression is ‘true’ or ‘false’, it
transfers the control to a particular statement. the if statements may
implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
1. simple if statement
2. if……else statement
3. Nested if…..else statement
4. else if ladder
22

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

True-block statements False-block statements

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

THE SWITCH STATEMENT


When one of the many alternatives is to be selected, we can use
if statement to control but it makes the programming very
complex. But C has a built-in multiway decision statement known as
switch. The switch statement tests the value of a given variable
against a list of case values and when a match is found, a block of
statement associated with that case is executed. The general form is:
29

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

Consider the example: Stmnt x

……………..
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

Syntax: conditional exp ? exp 1 : exp 2


The conditional expression is evaluated first. If the result is nonzero
(true) expression 1 is evaluated and is returned as the value of the
conditional expression. Otherwise, expression 2 is evaluated and its
value is returned. For example:
………………
flag = (x < 0) ? 0 : 1; This can be written as
if (x < 0)
flag = 0;
else
flag = 1;
THE GOTO STATEMENT
C supports the goto statement to branch unconditionally from
one point to another in the program. The goto requires a label in order
to identify the place where the branch is to be made. A label is any
valid variable name, and must be followed by a colon. The label is
placed immediately before the statement where the control is to be
transferred. The general form is:
goto label; label:
…………………… statement;
……………………. OR …………………..
label: …………………..
statement; goto label;
Forward jump Backward jump

DECISION MAKING AND LOOPING


32

The C language provides three constructs for performing loop


operations. They are:
1. the while statement
2. the do statement
3. the for statement
THE WHILE STATEMENT
The simplest of all the looping structures in c is the while
statement. The basic format is:
While (test condition)
{
Body of the loop
}
The while is an entry controlled loop statement. the test condition is
evaluated and if the condition is true, then the body of the loop is
executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. This
process of repeated execution of the body continues until the
test condition finally becomes false and the control is transferred out
of the loop. The body of the loop may have one or more statements.
Consider the example:
………………..
sum=0;
n=1;
while (n <= 10)
{
sum = sum +n*n;
n = n+1;
}
printf(“sum = %d”, sum);
………………….
33

THE DO STATEMENT

Você também pode gostar