Vous êtes sur la page 1sur 19

1 Basics of C

PIC-17212

Chapter 1: Basics of C
History of C, where C stands
C character set, tokens, constants, variables, keywords
C operators (arithmetic, Logical, assignment, relational, increment and decrement, conditional,
bit wise, special, operator precedence), C expressions data types.
Problem solving techniques : flowchart and algorithm
Formatted input, formatted output instructions.
(18M)

History of C:
C is a programming language developed at AT & Ts Bell Laboratories, USA in 1972. It was
designed and written by Dennis Ritchie.
C is the result of development process that started with a language called CPL (Combined
Programming Language). CPL was developed in 1963 at Cambridge University. CPL was very big
with too many features. It was hard to learn.
CPL was modified into BCPL (Basic CPL) by Martin Richards in 1967 at Cambridge University.
BCPL was not so powerful. In 1970, Ken Thompson at AT & Ts Bell Labs developed a language a
language called B. In 1972, Dennis Ritchie, combined some features of BCPL and B languages and
added some of his own features to develop C language.

Where C stands:
All the programming languages can be divided into two categories:
1) Problem oriented languages/ High Level Languages (HLL):
These languages are designed to give better programming efficiency i.e. faster and easy program
development e.g. FORTRAN, BASIC, Pascal etc.
2) Machine oriented languages/ Low Level Languages (LLL):
These languages are designed to give better machine efficiency i.e. faster program execution e.g.
Assembly language and machine language.
C stands in between these two categories therefore it is called a Middle Level Language. It has
features of both categories having good programming as well as machine efficiency.

C tokens:
In a paragraph, individual words and punctuation marks are called tokens. Thus, a token may be a
single character or a group of characters that is considered as a unit. There are six types of tokens
used in C. They are as follows:
1) Keywords (reserved words)

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

2) Identifiers (used to give names to variables, functions, constants etc.)


3) Literals (values)
4) Operators
5) Punctuation
6) Special symbols

The C character set:


A character denotes any alphabet, digit or special symbol used to represent data or information.
Following table shows the C character set:
A, B, C, , Z

Alphabets

A, b, c, , z
0, 1, 2, , 9

Digits

~ ! @ # % & ^ ( ) [ ]
Special symbols

{ } + - * / \ | < > : ;
? = _ (underscore) , .

Constants, Variable and keywords:


Constants:
A constant is a quantity that does not change. C constants are divided into two types:
C constants
______________ |_______________
|

Primary

Secondary

Integer

Array

Real

Pointer

Character

Structure
Union
Enum

Rules for writing integer constants:


1) An integer constant must have at least one digit.
2) It must not have decimal point.

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

3) It could be either positive or negative.


4) If no sign (+ or -) precedes integer constant, it is assumed to be positive.
5) No comma or spaces are allowed within an integer constant.
6) The range for integer constant is -32768 to 32767 (it depends on word size of computer. This is
the range for 16 bit computers).

Rules for writing real constants:


1) A real constant must have at least one digit.
2) It must have a decimal point.
3) It could be either positive or negative.
4) Default sign is +.
5) No comma or spaces are allowed within a real constant.
Exponential representation is used when value is too small or too large. Its general form is:
mantissa e exponent
Rules:
i) The mantissa and exponent should be separated by letter e.
ii) The mantissa and exponent both can have +ve or ve sign.
iii) Default sign for mantissa is +ve.
iv) The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is +ve.
v) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Rules for writing character constants:


1) A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single inverted commas. e.g.
A, 7, +

2) The maximum length of character constant is 1 character.

Variables:
A variable is an entity that may change during program execution. A variable is a named location in
computer memory that is used to store a value during program execution.

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

Rules for constructing variable names:


1) The maximum length of variable can be 31 alphabets, digits or special symbol (underscore). Some
computers allow only 8 characters, some allow 40 characters, and some allow up to 247 characters
also.
2) The first character in the variable name must be an alphabet or underscore.
3) No commas or blank spaces are allowed in a variable name.
4) No special symbol other than an underscore can be used in variable name.
Example:
s_name
rollNo
address_1
Variable declaration:
Before using variables, we have to declare them. Each variable has a data type. A variable will store
a value of its own data type. The syntax for variable declaration is:
data-type variable-name;

or

data-type variable-name-1, variable-name-2, , variable-name-n;

e.g.
int i;
int a,b,c;
float pi;
Variable initialization:
After declaration, if a variable is not given initial value, it will contain garbage value which is
undefined. The variables can be initialized at the time of declaration or at later time in the program.
The syntax for variable initialization is:
variable-name = value;
e.g.
int i;
i = 1;
The above two statements can be combined as follows:
int i = 1;
float pi = 22.0/7.0;

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

Keywords:
C keywords are the reserved words whose meaning has already been explained to the C compiler.
These keywords cannot be used to declare variables. There are 32 keywords available in C. They
are as follows:
auto

double

if

static

break

else

int

struct

case

enum

long

switch

char

extern

near

typedef

const

float

register

union

continue

far

return

unsigned

default

for

short

void

do

goto

signed

while

Data types:
All the characters, numbers, punctuation marks and other symbols are data. This data can be
classified into different types or categories. In C, data is classified into four basic types:
(i) Integer denoted as int
(ii) Float denoted as float
(iii) Double denoted as double
(iv) Character denoted as char
The storage space required to store these data types depends on word size of computer. Following
table shows basic data types and their respective memory requirement in number of bit. This size is
for 16 bit machines:

Sr.

Data types

No.

Memory requirement in bits

Range

int

16 bits (or 2 bytes)

-32768 to 32767

float

32 bits (or 4 bytes)

3.4e-38 to 3.4e38

double

64 bits (or 8 bytes)

1.7e-308 to 1.7e308

char

8 bits (or 1 byte)

-128 to 128

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

Type qualifiers:
Applying qualifiers to the basic data types, additional data types are obtained. A qualifier changes
the characteristic of data types, such as its size or sign. The qualifiers those alter the size are:
1) short
2) long
These qualifiers can be used with int data type e.g.
short int
long int
The long qualifier can be used with double data type also e.g. long double
The sign qualifiers are signed and unsigned. The sign qualifiers can be used with integer and
character data types (e.g. int, short int, long int, char, signed char, unsigned char). For int data
type, these can be combined with size qualifiers. Using size and sign qualifier with int we get 6 more
data types:
signed short int
unsigned short int
signed int
unsigned int
signed long int
unsigned long int
The size qualifiers cannot be applied to the char and float data types. Similarly, sign qualifiers
cannot be applied to float, double and long double.
Example: A C program to add two numbers:
#include<stdio.h>
#include<conio.h>
int main( )
{
int a, b, c;
clrscr( );
printf(Enter value of a: );
scanf(%d,&a);
printf(Enter value of b: );
scanf(%d,&b);
c = a + b;
printf(\nc=%d,c);
getch( );
return 0;
Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

C operators:
An operator is a symbol that operates on certain data type. For example, the operator + is used for
addition. In C, operators can be classified into various categories based on their use and action. The
different types of operators available in C are as follows:
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:
The arithmetic operators perform arithmetic operations like addition, subtraction, multiplication,
division. A list of arithmetic operators is given below:
Operator

Meaning

Addition

Subtraction

Multiplication

Division

Modulus

% operator is used to find remainder after division operation e.g.


10%2 will give remainder as 0 while
5%2 will give remainder as 1.
In C, it can be used only with integer numbers.

Relational operators:
These are also known as comparison operators. These operators are used to compare arithmetic,
logical and character expressions. The relational expression is evaluated to an integer value. It

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

evaluates to 0 if the condition is false, and evaluates to 1 if the condition is true. Relational operators
are as follows:
Operator

Meaning

<

less than

>

greater than

<=

less than or equal to

>=

greater than or equal to

==

equal to

!=

not equal to

Logical Operators:
A logical operator is used to compare or evaluate logical and relational expressions. There are 3
logical operators in C language. They are:
Operator

Meaning

&&

logical AND

||

logical OR

logical NOT

AND operator checks for all conditions to be true then only it returns true, otherwise it returns false.
OR operator checks for any one (or more than) condition to be true then it returns true. If all
conditions are false then OR operator returns false.
NOT operator takes only one expression and evaluates to true (i.e true) if the expression is false (i.e.
0), and evaluates to false if expression is true.
Assignment operators:
Assignment operators are used to assign the result of an expression to a variable. The syntax is:
variable = value or expression;
e.g
a = 10;

or

a = b + c;

etc.

In C, shorthand assignment operators are available. These are used as:


variable operator=expression;
e.g.
a += b;
The above statement is shorthand notation of following statement:

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

a = a + b;
Like + operator we can use other operators (-, *, /, % etc.).

Increment and Decrement operators:


Increment and decrement operators are used to increment or decrement value by 1. The increment
operator is written as ++ and decrement operator as --. These can be used as,
variable++ or ++variable
variable-- or --variable
For example, consider a variable n having value 10 i.e. n= 10;
When increment operator is applied to n like n++ or ++n then the value of n is incremented by 1. It
will become 11.
Similarly if value of n=10 and decrement operator is used:
n--; or --n;

then after execution of this instruction, n will contain 9.

Basically ++i; and i++; have the same effect i.e. both will increment the value of i by 1. Both
statements will behave differently when used in an expression. Consider following example:
Let i =10;
a = i++;
After executing above statement, value of variable a will be 10 and value of variable i will become
11. This is because, in the above statement, current value of variable i will be assigned to variable a
first, then it will be incremented by 1.
Now let i =10;
a = ++i
After executing above statement, value of variable a will be 11 and value of variable i will become
11. This is because, in the above statement, current value of variable i will be incremented by 1 first,
then it will be assigned to variable a.
Similarly for decrement operator.

Conditional operator:
The conditional operator consists of two symbols ? : . It is called ternary operator because it uses
three expressions. Its syntax or general form is:
variable = conditional expression ? expression1 : expression2;

Computer Department, Jamia Polytechnic (0366)

1 Basics of C

PIC-17212

In the above statement conditional expression is evaluated first. If its value is true, then
expression1s value is assigned to the variable on left hand side. If the conditional expraession is
false, then expression2s value is assigned to the variable.
e.g.
large = i > j ? i : j;
In the above statement, if value of i is greater than value of j, value of i is assigned to variable large.
If value of j is greater than value of i, large is assigned with the value of j.

Bitwise operators:
Bitwise operators are used to manipulate the data at bit level. Any information in computer is
represented using binary digits (also called as bits). Binary digits are 0 and 1. So if you want to
perform operations on bits, bitwise operators can be used. Following table shows bitwise operators:
Operator

Meaning

&

bitwise AND operator

bitwise OR operator

bitwise EXOR operator

<<

shift left

>>

shift right

bitwise complement

Following tables show different bitwise operators applied to two bits:

& oprator:
Bit 1

Bit 2

&

If all bits are 1, & gives result as 1.

Computer Department, Jamia Polytechnic (0366)

10

1 Basics of C

PIC-17212

| oprator:
Bit 1

Bit 2

Bit 1

Bit 2

If any of the bits is 1, | gives result as 1.


^ oprator:

If bits are different, ^ operator gives result as 1.

~ oprator:
Bit

~ complements bits i.e. converts 0s to 1s and 1s to 0s.

Examples: Consider 3 integer variables:


int a = 13, b = 7, c;
In binary form:
a = 0000 0000 0000 1101
b = 0000 0000 0000 0111

Bitwise AND:
c = a & b;

Computer Department, Jamia Polytechnic (0366)

11

1 Basics of C

PIC-17212

0000 0000 0000 1101

0000 0000 0000 0111


---------------------------------

a&b

0000 0000 0000 0101

=5

Bitwise OR:
c = a | b;
a

0000 0000 0000 1101

0000 0000 0000 0111


---------------------------------

a|b

0000 0000 0000 1111

= 15

Bitwise EXOR:
c = a ^ b;
a

0000 0000 0000 1101

0000 0000 0000 0111


---------------------------------

a^b

0000 0000 0000 1010

= 15

Left shift operator:


The left bit-shift operator << is used to shift the bits of integer variable to left side. Its syntax is:
variable1 = variable2 << n;
Here bits of variable2 will be shifted to left by n bit position.
e.g. let a = 13
c = a << 3;
a

0000 0000 0000 1101

insert 0s from right side

a << 3

0000 0000 0110 1000

= 104

Right shift operator:


The right bit-shift operator >> is used to shift the bits of integer variable to right side. If variable
has positive value, 0s will be filled from left side. Its syntax is:
variable1 = variable2 << n;
Here bits of variable2 will be shifted to left by n bit position.
e.g. let a = 13

Computer Department, Jamia Polytechnic (0366)

12

1 Basics of C

PIC-17212

c = a >> 2;
a

0000 0000 0000 1101

insert 0s from left side

a >> 2

0000 0000 0000 0011

=3

Negative numbers are represented in 2s complement form. To find 2s complement of any number,
take binary representation of that number, complement its bits i.e. convert 0s into 1s and 1s into 0s.
After complementing, add 1 to it. the number you will get is 2s complement:
e.g. let a = 3.
Binary equivalent of 3 is
3

0000 0000 0000 0011

Complement the bits:


1111 1111 1111 1100
Add 1 to this sequence to get 2s complement:
1111 1111 1111 1100
1
--------------------------------1111 1111 1111 1101
The above result is binary representation of -3.
The statement
c = a >> 2;
will shift the bits of a by 2 bit position and 1s will be filled from left side.
a >> 2

1111 1111 1111 1111

This number is in 2s complement form and is equivalent to -1;

Special operators:
Special operators are as follows:
sizeof
, (comma)
* and &
-> and . (dot)
The operator sizeof gives the size of the data type or the variable in terms of number of bytes used by
that data type or variable. Comma , operator is used in separating variable names while they are
declared, for example,
Computer Department, Jamia Polytechnic (0366)

13

1 Basics of C

PIC-17212

int i, j, k;
or it is used in for loop to separate multiple initialization expressions and update expressions, for
example,
for(int i=0, j=size-1; i<size/2; i++, j--)
{

}
* and & are pointer operators.
-> and . are member selection operators.

Operator precedence:
Precedence means priority. In a single expression there may be multiple operators. In this situation,
to evaluate the expression, the compiler follows certain rules. These rules explain which operator
will be applied first. Lets take an example:
Consider
int a = 10, b = 15, c = 3, d;
d = a + b * c;
In the above expression, * operator will be applied first because it has higher priority. So, first of
all b is multiplied by c. The result is then added to a. After this, the final result will be assigned to d.
steps:

d = a + b * c;
d = 10 + 15 * 3;
d = 10 + 45;
d = 55;

Associativity:
Associatity describes how operands are associated with operators: either from left side to right side
or from right side to left side. e.g. -5, in this example, the operand on right side is associated to the
operator on left side, so, unary minus has assocativity from right to left. In general unary operators
(which operate on one operand), ternary operator (which have 3 operands e.g. conditional operator
? : ) and assignment operators have associativity from right to left. All binary operators (which take 2
operands) have associativity from left to right.
Following table shows different operators and their precedence.

Computer Department, Jamia Polytechnic (0366)

14

1 Basics of C

PIC-17212

Operator

Precedence

Associativity

( ) [ ] -> .

Left to Right

! ~ + (unary plus) - (unary minus) ++

Right to Left

* / %

Left to Right

+ (addition) - (subtraction)

Left to Right

<< >>

Left to Right

< <= > >=

Left to Right

== !=

Left to Right

&

Left to Right

Left to Right

10

Left to Right

&&

11

Left to Right

||

12

Left to Right

?:

13

Right to Left

= *= /= %= += -= &= ^= |=

14

Right to Left

-- & sizeof

<<= >>=

Formatted Input:
Input is the process of accepting values from user i.e. from input device such as keyboard or mouse.
Formatted input data is the data which is arranged in a particular format. The data consists of
characters, numbers or digits (floating point/integer values), symbols etc. In C to read data, scanf( )
function is used. The syntax or general form of scanf( ) is as follows:
scanf(control string , arg 1, arg 2, , arg n);
In the above general form, control string specifies what type of data scanf( ) function will accept
from the user. The data entered by user will be stored in arguments arg 1, arg 2, , arg n. Except for
string arguments, the arguments are preceded by & symbol e.g. &arg 1.
Control string contains 3 types of objects:
1) Whitespace characters
2) Ordinary characters
3) Format specifiers

Computer Department, Jamia Polytechnic (0366)

15

1 Basics of C

PIC-17212

Format specifier is a combination of % character and data type specifier. An optional field with
value can also be used in format specifier. Following table shows data type specifiers:
Code

Meaning

%c

Read a single character

%d

Read a decimal integer

%e

Read a floating point value

%f

Read a floating point value

%g

Read a floating point value

%h

Read a short integer

%i

Read a decimal, hexadecimal or octal integer

%o

Read an octal integer

%s

Read a string

%u

Read an unsigned decimal integer

%x

Read a hexadecimal integer

Format specifiers can contain integer value after % symbol for reading integer and character data.
e.g. %4d, it will scan 4 digits to be stored in an integer variable. The statement scanf(%2d, &num)
will accept 2 digits for num variable and discard rest of digits entered by user.

Formatted output:
To output the data or message, printf( ) function is used. Syntax or general form of printf( ) function
is as follows:
printf(control string, arg 1, arg 2, , arg n);
Control string consists of message, format specifiers and escape sequences.
Format specifiers are shown in following table:

Computer Department, Jamia Polytechnic (0366)

16

1 Basics of C

PIC-17212

Format specifier

Meaning

%d

decimal integer

%i

signed decimal integer

%u

unsigned decimal integer

%o

octal number

%x

unsigned hexadecimal number

%f

floating point value

%e

floating point value in exponential notation

%g

floating point value

%c

single character

%s

string value

The letters h, l, L can be used in format specifiers.


h is used for printing short integers

l is used for long integers and doubles


L is used for long doubles.
e.g.
%ld is used for long integer decimals.
+, - flags can be used to justify the output to left or right, and display +, - sign before number.
0 is used to display leading 0s.
e.g.

Statement

Output

printf(%d,1234);

printf(%6d,1234);

printf(%2d,1234);

printf(%-6d,1234);

printf(%06d,1234);

printf(%+d,1234);

printf(%+d,-1234);

Program #1: To display hexadecimal, decimal, octal forms of the entered integer number:
#include<stdio.h>
#include<conio.h>
int main( )
Computer Department, Jamia Polytechnic (0366)

17

1 Basics of C

PIC-17212

{
int n;
clrscr( );
printf("Enter a number : );
scanf(%d,&n);
printf("The hexadecimal equivalent of number: %x",n);
printf("\nThe decimal equivalent of number: %d",n);
printf("\nThe octal equivalent of number: %o",n);
getch();
return 0;
}
Output:
Enter a number : 15
The hexadecimal equivalent of number: f
The decimal equivalent of number: 15
The decimal equivalent of number: 17

Program #2: To display number with leading 0s and trailing 0s:


#include<stdio.h>
#include<conio.h>
int main( )
{
int n;
float f;
clrscr( );
printf("Enter an integer number : );
scanf(%d,&n);
printf("Enter a floating point number : );
scanf(%f,&f);
printf("The integer number without leading 0s: %d",n);
printf("\n The integer number with leading 0s: %7d",n);
printf("\nThe floating point number with trailing 0s: %f",f);
printf("\nThe floating point number with less trailing 0s: %7.4f",f);
getch();
return 0;
}
Output:
Enter an integer number : 123
Enter a floating point number : 2.25
The integer number without leading 0s: 123
The integer number with leading 0s: 0000123
The floating point number with trailing 0s: 2.250000
The floating point number with less trailing 0s: 2.2500
Computer Department, Jamia Polytechnic (0366)

18

1 Basics of C

PIC-17212

Program #3: To display number with right justification and left justification:
#include<stdio.h>
#include<conio.h>
int main( )
{
int n;
clrscr( );
printf("Enter a number: );
scanf(%d,&n);
printf("\nThe number with right justification:%7d$",n);
printf("\nThe number with left justification:%-7d$",n);
getch();
return 0;
}
Output:
Enter a number:123
The number with right justification: 123$
The number with left justification:123 $

End of Chapter 1

Computer Department, Jamia Polytechnic (0366)

19