Unit 2
Unit 2
C LANGUAGE
C was invented in 1972 at AT & T Bell labs by Dennis Ritchie. Dennis
Ritchie was also involved in writing a new Operating System called Unix
along with other scientists Ken Thompson and Brian Kernighan. C was
extensively used in Unix about 90% of the code in Unix is in C.
Features of C language:
• Structured
• High Level/Middle Level
• Robust
• Portable
• Supports pointers
• Extensible
1
Structured:
C is structured procedure-oriented language, it divides the problem
into smaller modules called functions or procedures.
Portable:
C is portable that is code written on one machine can be easily
ported or executed on other machines as long as that machine supports
the same C compiler.
Robust:
C is robust language that is programs written in C do not crash so
easily. It recovers quickly whenever programs results into an erroneous
condition.
Extensible:
C is extensible language that is it allows new features and
modifications to be made to the existing programs written in C.
Supports pointers:
C supports the use of pointers that allows the programmers to
manipulate the memory directly.
CHARACTER SET
• Character-set refers to the set of alphabets, letters and some special
characters that are valid in C language.
• For example, the characters in C are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
2
→ Symbols such as + - * / % # @ ‘ ] { “ $ etc.
→ White spaces
TOKENS
• A token is a smallest element of a C program.
• One or more characters are grouped in sequence to form
meaningful words. These meaningful words are called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while, int, float, char
→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "sri"
→ Operators ex: + - * /
→ Special symbols ex: [], (), {}
KEYWORDS
3
• Following keywords are as listed below:
IDENTIFIER
• Identifier is used to represent various parts of a program such as
variables, constants, functions etc.
• An identifier is a word consisting of sequence of
→ Letters
→ Digits or "_"(underscore)
• For ex:
Average,_Percent, total100
CONSTANTS
• A constant is an identifier whose value remains fixed throughout the
execution of the program.
• The constants cannot be modified in the program.
4
• For example:
1, 3.14512 , ‘z’, “pcdnotes"
i) Fractional Form
• A floating point number represented using fractional form has an
integer part followed by a dot and a fractional part.
• For ex:
0.5, -0.99
ii) Scientific Notation (Exponent Form)
• The floating point number represented using scientific notation has
three parts namely:
mantissa E exponent
5
• For ex:
9.86E3 imply 9.86*103
3) Character Constant
• A symbol enclosed within a pair of single quotes(') is called a
character constant.
• Each character is associated with a unique value called an ASCII
(American Standard Code for Information Interchange) code.
For ex: '9', 'a', '\n'
4) String Constant
• A sequence of characters enclosed within a pair of double quotes(“) is
called a string constant.
• The string always ends with NULL character (denoted by \0) character.
• For ex:
"9" "a" "sri" "\n"
6
OPERATOR
• An operator can be any symbol like + - * / that specifies what operation
need to be performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation Operand
CLASSIFICATION OF OPERATORS
Operator Name For Example
Arithmetic operators +-*/%
Increment/decrement operators ++ --
Assignment operators =
Relational operators < > ==
Logical operators && || ~
Conditional operator ?:
Bitwise operators &|^
Comma operator ,
Special operators [], sizeof,→
7
ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations such as
addition, subtraction,
#include<stdio.h>
int main()
{
int a=11,b=4,c;
c=a+b;
printf("a+b=%d \n", c);
c=a-b;
printf("a-b=%d \n", c);
c=a*b;
printf("a*b=%d \n", c);
c=a/b;
printf("a/b=%d \n", c);
8
c=a%b;
printf("Remainder when a is divided by b=%d ", c);
return 1;
}
Output:
a+b=15
a-b=7
a*b=44
a/b=2
Remainder when a is divided by b= 1
INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is
used to increase the value of a variable by 1.
• For example:
If b=5
then b++ or ++b; // b becomes 6
• The increment operator is classified into 2 categories:
1) Post increment Ex: b++
2) Pre increment Ex: ++b
DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is
used to decrease the value of a variable by 1.
• For example:
If b=5
then b-- or --b; // b becomes 4
• For ex:
If x=10,
then z= x--; // z becomes 10,
but z = --x; // z becomes 9
Example: Program to illustrate the use of decrement operators.
int main()
{
int x=10,y = 10, z ;
z= x--;
printf(“ z=%d x= %d\n”, z, x);
10
z = --y;
printf(“ z=%d y= %d”, z, y);
}
Output:
z=10 x=9
z=9 y=9
ASSIGNMENT OPERATOR
• The most common assignment operator is =.
• This operator assigns the value in right side to the left side.
• The syntax is shown below:
variable=expression;
• For ex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to b
5=c; // Error! 5 is a constant.
• The operators such as +=,*= are called shorthand assignment operators.
• For ex,
a=a+10: can be written as a+=10;
RELATIONAL OPERATORS
• Relational operators are used to find the relationship between two
operands.
• The output of relational expression is either true(1) or false(0).
• For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
• The 2 operands may be constants, variables or expressions.
11
There are 6 relational operators:
Operator Meaning of Operator Example
> Greater than 7>4 returns true (1)
< Less than 7<4 returns false (0)
>= Greater than or equal to 7>=4 returns true (1)
<= Less than or equal to 7<=4 return false (0)
== Equal to 7==4 returns false (0)
!= Not equal to 7!=4 returns true(1)
• For ex:
Condition Return values
8> 7 1 (or true)
8>7 0 (or false)
8+7<15 0 (or false)
• Example: Program to illustrate the use of all relational operators.
#include<stdio.h>
int main()
{ printf(“7>4 : %d \n”, 7>4);
printf(“7>=4 : %d \n”, 7>=4);
printf(“7<4 : %d \n”, 7<4);
printf(“7<=4 : %d \n”, 7<=4);
printf(“7==4 : %d \n”, 7==4);
printf(“7!=4 : %d ”, 7!=4);
return 1;
Output:
7>4 : 1
7>=4 : 1
7<4 : 0
7<=4 : 0
7==4 : 0
7!=4 : 1
12
LOGICAL OPERATORS
• These operators are used to perform logical operations like negation,
conjunction and disjunction.
• The output of logical expression is either true(1) or false(0).
• There are 3 logical operators:
13
Output:
5 && 0 : 0
5 || 0 : 1
!0 : 1
#include<stdio.h>
int main()
{
printf(“7>5 && 5< 8 : %d \n”, 7>5 && 5<8);
printf(“ 7<5 || 5==5 : % d \n”, 7<5 || 5==5);
printf(“!(3 ==3) : %d ”, !(3==3));
return 1;
}
Output:
7>5 && 5<8 : 1
7<5 || 5==5 : 1
!(3 ==3) : 0
14
Example: Program to find biggest of 2 numbers using conditional operator.
#include<stdio.h>
int main()
{
int a,b, big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d”, &a, &b);
big=(a>b)? a : b;
printf(“ Biggest number is ”, big);
return 1;
}
Output:
Enter two different numbers: 88 79
Biggest number is 88
#include<stdio.h>
int main()
{
int a,b,c big ;
printf(“Enter two different numbers:\n”);
scanf(“%d%d%d”, &a, &b, &c);
big=(a>b)? ((a>c)?:a:c) : (b>c)?b:c ;
printf(“ Biggest of three number is ”, big);
return 1;
}
Output:
Enter two different numbers: 88 79 99
Biggest number is 99
15
BITWISE OPERATORS
• These operators are used to perform logical operation (and, or, not) on
individual bits of a binary number.
• There are 6 bitwise operators:
a = 12 00001100 b= 15 00001111
~a= 11110011 ~b = 11110000
a & b 0000 1100
• The operator that is used to shift the data by a specified number of bit
positions towards left or right is called shift operator.
• The syntax is shown below for << The syntax is shown below for >>
b=a << num; b=a >> num; where a is value to be shifted
16
and num is number of bits to be shifted.
Comma Operator:
The comma operator (represented by the token ,) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the second
operand and returns the value (and type). The comma operator has the lowest
precedence of any C operator.
int x , y;
y=(x=10,x=x+20);
printf(“x=%d”,x);
Output:
x=30, y=30;
17
User defined function-definition(s)➔ optional
Documentation Section
• This section allows to document by adding Comments to the
program. Comments are portions of the code ignored by the
compiler. The comments allow the user to make simple notes in the
source-code.
• For ex. // this is an example for single line comment
/* this is an example for multiple line comment */
Link Section
This section contains the header files to be included if any inbuilt functions
have been used by the program. For ex. If sqrt() function has been used to
find the square root then #include<math.h> needs to be included.
Generally, #include<stdio.h> header is always included because most
programs would be using input or output functions such as scanf() and
printf().
Preprocessor Directives
• The preprocessor accepts the source program and prepare the source
program for compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to
include the specified file-contents in the beginning of the
program.
• For ex:
#include<stdio.h>
main()
Global declaration section
• If user wishes to declare any variable outside the main program
which needs to be accessed by any part of the program then he may
declare it in this section just before main function.
18
• Every C program should have a function called as main() and is an entry
point to the program (a gateway to the program) that is always executed.
• The statements enclosed within left and right curly brace is called body
of the function. The main() function is divided into 2 parts:
Declaration Section
• The variables that are used within the function main() should be
declared in the declaration-section only.
• The variables declared inside a function are called local-variables.
The compiler allocates the memory for these variables based on
their types for ex. if the variable is an integer then it allocates 4
Bytes, if it’s of char type then 1-Byte and so on. Ex: int p, t, r;
Executable Section
• This contains the instructions given to the computer to perform a
specific task.
• The task may be to:
→ display a message
→ read data or
→ do some task ex. add two numbers etc.
#include<stdio.h>
int main()
{
printf(“Welcome to C”);
return 1;
}
Output:
Welcome to C
19
Life cycle of a C program
Source Executable
Pre- Object Linking
Program Compile File
process file
(P1.o) (P1.exe)
(P1.c)
Library files
Source Program: Any C file say P1.C program is edited and given to a C
compiler. Figure above shows the different phases of
execution of C program.
Pre-Processing: This is the first phase through which source code is passed. In
this phase any statements defined in this section (before the main()
function) are processed, if used in the program.
This phase includes:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
• Conditional compilation
For ex. printf and scanf statements, if used in the program, will have been
checked with their definitions stored in the header file <stdio.h>.
Compile: The next step is to compile and produce an; intermediate file that
contains assembly level instructions P1.s.
During this phase the compiler checks for the syntax errors such as
declaration of variables, initialization if any, the correct syntax of the C
program etc. If any errors are encountered then they get displayed with
corresponding line numbers.
The assembler converts the P1.s file after correction and successful
compilation of the program to an object file P1.o.
20
Linking:
This is the final phase in which all the linking of function calls with their
definitions are done. Linker knows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program
which is required when the program starts and ends.
Loader:
Loader takes the image (P1.exe) generated and loads it into RAM and informs
the CPU the starting address of the code for execution (running of the
program).
3) char
• A char is a keyword which allows defining and store a single
character.
• Compiler allocates 1 byte of memory.
4) void
• void is an empty data type indicates that no value is associated with this
data type, and it does not occupy any space in the memory.
• Generally used with functions to indicate that the function does not
return any value.
22
Range of data types for 16-bit processor
Data type Bytes Range of data type
char 1 byte -128 to 127
unsigned char 1 byte 0 to 255
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
float 4 bytes 3.4E-38 to 3.4E38
double 8 bytes 1.7E-308 to1.7E308
long 8 bytes -223372036854775808 to
+9223372036854775807
unsigned long 8 bytes 0 to
18446744073709551615
Qualifiers
• Qualifiers alter the meaning of primary data types to yield a new data
type.
Size Qualifiers
• Size qualifiers alter the size of primary data type.
• The keywords long and short are 2 size qualifiers.
For example:
long int i; //The size of int is 2 bytes but, when long
//keyword is used, variable will be of 4 bytes
short int i; //The size of int is 2 bytes but, when short
//keyword is used, that variable will be of 1
//byte
Sign Qualifiers
• Whether a variable can hold positive value, negative value or both
values is specified by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
23
unsigned int a; //unsigned variable can hold zero &
// positive values only
signed int b; //signed variable can hold zero , positive
//and negative values
Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An identifier declared by using a const keyword cannot be modified.
VARIABLE
• A variable is an identifier whose value can be changed during execution
of the program. Variable is a name given to a memory-location where the
data(value) can be stored.
• Valid variables:
area, rate_of_interest, _temperature_, celcius25
Invalid variables:
3fact, ?sum, sum-of-digits, length62$, for,
int, if
24
Declaration of Variable
• The declaration tells the complier
• what is the name of the variable used
• what type of data is held by the variable
• The syntax is shown below:
data_type variable1, variable2, variable3;
where variable1, variable2, variable3 are variable-names
of data_type that could be int, float or char type.
• For ex:
int a, b, c;
float x, y, z;
Initialization of Variable
• The variables are not initialized when they are declared. Hence, variables
normally contain garbage values and hence they have to be initialized with
valid data.
data_type variable_name
float pi=3.1416;
char c='z';
Input Function
• The input functions are used to read the data from the keyboard and
store in memory-location.
• For ex:
scanf(), getchar(), getch(), getche(), gets()
Output Functions
• The output functions are used to receive the data from memory-
locations through the variables and display on the monitor.
• For ex:
printf(), putchar(), putch(), puts()
26
UNFORMATTED I/O
getchar() and putchar()
• getchar() is used to
➢ reads a character from the keyboard and stores the character into a
memory-location or buffer.
• After typing a character ENTER key needs to be pressed.
• The syntax is shown below:
char variable_name = getchar( );
• For ex:
char z;
z= getchar( );
• putchar() is used to display a character stored in the memory-location on
the screen.
#include<stdio.h>
int main()
{
char x;
printf(“Type a character followed by ENTER key: \n”);
x = getchar();
putchar(x); // same as printf(“%c”, x);
return 1;
}
Output:
Type a character followed by ENTER key: N
N
#include<stdio.h>
int main()
{
char x;
printf(“Type a alphabet: \n ”);
x = getch();
putch(x);
return 1;
}
Output:
Type a alphabet: K //K is not visible
K prints K to the output screen
FORMATTED I/O
scanf()
• Input function to read data from the keyboard
• The scanf function does the following tasks:
→ Scans a series of input fields one character at a time
→ Formats each field according to a corresponding format-specifier
passed in format-string (format means convert).
→ Stores the formatted input at an address passed as an argument i.e.
address-list
• Syntax is shown below:
scanf("formatted-string", address-list);
where formatted-string contains one or more format-specifiers address-
list is a list of variables. Each variable name must be preceded by &
• For ex:
int x;
float y;
char z;
scanf("%d %f %c", &x, &y, &z);
printf
The printf function does the following tasks:
→ Accept a series of arguments
→ Applies to each argument a format-specifier contained in the format-
string
→ Prints the formatted data to the screen
• The syntax is shown below:
printf("format-string", variable-list);
where format-string contains one or more format-specifiers
variable-list contains names of variables
• For ex:
printf("%d %f %c", x, y, z );
• Example: Program to read age of a person and display the same to the
screen.
#include<stdio.h>
int main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”, &age);
printf(“Your age is %d years ”, age);
return 1;
}
Output:
Enter your age:21
Your age is 21 years
30
VARIATIONS IN OUTPUT FUNCTION FOR INTEGER AND FLOATS
#include<stdio.h>
int main()
{
printf("%6d \n",9876);
// Prints the number right justified within 6 columns
printf("%3d \n",9876);
// Prints the number to be right justified to 3 columns but, there are 4
//digits so number is not right justified
printf("%.2f \n",987.6543);
// Prints the number rounded to two decimal places
printf("%.f \n",987.6543);
// Prints the number with six decimal places
printf("%e ",987.6543);
// Prints the number in exponential notation(scientific //notation)
return 1;
}
Output:
9876
9876
987.65
988
9.876543e+002
31
TYPE CONVERSION
• Type conversion is used to convert data of one type to data of another
type.
• Type conversion is of 2 types as shown in below figure:
Conversion Hierarchy:
Any implicit type conversions are made by converting the lower type to
higher type as shown below:
IMPLICIT CONVERSION
• If a compiler converts one type of data into another type of data
automatically, it is known as implicit conversions.
• There may be data loss whenever in implicit conversion takes place i.e
while converting from float to int the fractional part will be truncated,
double to float causes rounding of digit and long to int causes dropping of
excess higher order bits.
• The conversion always takes place from lower rank to higher rank.
EXPLICIT CONVERSION
• When the data of one type is converted explicitly to another type with
the help of some pre-defined types, it is called as explicit conversion.
• The syntax is shown below:
data_type1 v1;
#include<stdio.h>
int main()
{
int b=11;
int c = 22;
float d;
d=(float)b/c;
printf("d Value is : %f ", d );
return 0;
}
Output:
d Value is : 0.500000
PRECEDENCE TABLE
Rank Operator Associativity Rank Operator Associativity
1 () Left to Right 9 ^ (Bitwise Left to right
[] XOR)
.
→
++ --
2 - Unary minus Right to left 10 | (Bitwise OR) Left to Right
++ (prefix
increment)
- - (prefix
34
decrement)
~ (one’s
complement)
* (indirection
Or
dereference)
& (Address of)
! (Logical Not)
(type) type cast
sizeof
3 * / % (Modulus ) Left to Right 11 && Left to Right
4 + - (Binary Left to Right 12 || Left to Right
Addition or
Subtraction)
5 << >> Left to Right 13 ?: (Ternary Right to left
operator)
6 < >= Left to Right 14 = Right to left
` < <= +=
-=
*=
/=
>>= etc.
7 == != Left to Right 15 , Left to Right
8 & (Bitwise AND) Left to Right
Output:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
36