BCP Unit Ii
BCP Unit Ii
Introduction to C
History of C Language
Why Learn C?
There are a large number of programming languages in the world today—C++, Java,
Ada, BASIC, COBOL, Perl, Pascal, Smalltalk, FORTRAN, etc. Even so, there are several reasons
to learn C, some of which are stated as follows.
Standardizations of C Language
• Both UNIX and C were created at AT&T’s Bell Laboratories in the late 1960s and early
1970s. During the 1970s the C programming language became increasingly popular.
• During the late 1970s and 1980s, versions of C were implemented for a wide variety
of mainframe computers, minicomputers, and microcomputers, including the IBM
PC.
• In the early 1980s, a need was realized to standardize the definition of the C
language which in turn would help C become more widespread in commercial
programming.
• In 1983 the American National Standards Institute (ANSI) formed a committee to
establish a standard specification of C known as ‘ANSI C’.
• This work ended in the creation of the so-called C89 standard in 1989. This version of
the language is often referred to as ANSI C, Standard C, or sometimes C89.
ISO/IECSO/IEC (It is a joint technical committee (JTC) of the International
Organization for Standardization (ISO) and the International Electro technical
Commission (IEC)).
• In 1990, the ANSI C standard (with a few minor modifications) was made by the
International Organization for Standardization (ISO) as ISO/IEC 9899:1990. This
version is sometimes called C90. Therefore, the terms ‘C89’ and ‘C90’ refer to
essentially the same language.
C Tokens
These are smallest individual units. They may represent a single character (or) a group
of characters which has a specific meaning.
The following are the ‘C’ tokens that can be recognized by “C compiler”.
C Tokens
C Character Set
The characters are used to form words, numbers and expressions, and statements. C
Character set includes the following:
Alphabet:
Letters: Uppercase A to Z, Lowercase a to z.
Digits: All decimal digits from 0 to 9
Whitespaces: Blankspace
Horizantal Tab
Vertical Tab
New Line
Formfeed
Special Characters:
Symbo Symbo
Name of the character Name of the character
l l
, Comma = Equal to
‘ Apostrophe ^ Caret
Backslash (Backward
\ < Less Than
slash)
~ Tilde () Paranthesis
_ Underscore [] Brackets
% Percentage {} Braces
Delimiters:
Language pattern of ‘C’ uses special kind of symbols called as Delimiters.
Delimiter Purpose
# Pre-processor directive
, ( Comma) Separator
/* ……….. */ Comments
Identifiers
These are the names that are given to the various program elements such as
variables, functions, arrays, structures, etc.
These are user defined names.
Rules to be followed for Identifiers:
They should start with an alphabet but not any other character except
underscore.
It should not start with a digit.
C is case sensitive, hence uppercase and lowercase characters are significant.
It should not be a keyword.
It should be a meaningful name, so as to reflect its use.
Whitespace between the identifiers is not allowed, means identifier should be a
single word, but to join the words we can use underscore (_).
The length of an identifier changes from compiler to compiler.
Following are the some of valid and invalid identifiers
Valid Invalid
Name 3name
MAX @MAX
_sum -sum
Keywords
These are the words reserved by the compiler, hence they are also called
Reserved words whose meaning and purpose is defined in advance.
They should be in lower case.
There are 32 keywords supported by C and standardized by ANSI and these
serve as the basic building blocks of a program statements.
Following are the ANSI C keywords.
do if static while
Constants
These are defined as the fixed values, which doesn’t undergo any change during the
execution a program.
Constants
Numeric Constants:
1. Integer Constants:
These are the sequence of numbers from 0 to 9 without decimal points or
fractional part or any other symbol.
The number without sign is assumed as positive.
Ex: 187, 15, 25689, -25, -45, -854 etc.,
2. Real Constants:
These are often known as Floating-point constants.
Since integer constants are unfit to represent some quantities like length, weight,
height, volume, area, percentage, currency etc.,
Integer results for some operations will give approximate results, but real
constants gives accurate results, hence to improve accuracy, we will prefer real
constants.
It has two parts Integer part and fractional part.
Ex: 256.652, 45.623, 5.436 etc.,
Character Constants:
1. Single Character Constants:
It is a single character enclosed within a pair of single quote marks (‘ ‘).
These constants include a single letter, single digit, single special character or a
whitespace.
Ex: ‘a’, ‘$’, ‘&’, ‘5’ etc.,
Note: All character constants have integer values known as ASCII values. ASCII
stands for American Standard Code for Information Interchange.
2. String Constants:
These are sequence of characters enclosed within double quotes (“ “).
It is a combination of all kinds of characters, digits and symbols.
Ex: “good”, “Hello”, “2563”, “f@ct”, “56&&” etc.,
‘\\’ Backslash 92
Data types
signed int
Signed
(or) 2 -32768 to +32767 %d
Integer
int
(or)
Signed Short
short int 1 -128 to +127 %d
Integer
(or)
short
(or) -2147483648
Signed Long
long int 4 to %ld
Integer
(or) +2147483647
long
unsigned int
Unsigned
(or) 2 0 to 65535 %u
Integer
unsigned
Floating point or Real numbers data type should be identified for those quantities to be
represented with fractions.
Keyword Size Format
Data Type Range
Equivalent (In Bytes) Specifier
Floating
float 4 3.4E-38 to 3.4E+38 %f
point
Double Data
double 8 1.7E-308 to 1.7E+308 %lf
Type
Long Double
long double 10 3.4E-4932 to 3.4E+4932 %lf
Data Type
Character
char
or
(or) 1 -128 to +127 %c
Signed
signed char
Character
Unsigned unsigned
1 0 to 255 %c
Character char
Variables
When a program is executed many operations are carried on data. These data are stored
in memory in the form of variables.
Definition: A variable is defined as a data name used for storing a data value. In other
words it is a named memory location.
A variable may take different values at different times during execution, means it’s value
may varies (changes).
A variable name can be chosen by the programmer in a meaningful way, so as to reflect
it’s purpose.
Ex: marks, student, average, sum, num, fact etc.,
Rules for defining variables:
They should start with an alphabet but not any other character except
underscore.
It should not start with a digit.
C is case sensitive, hence uppercase and lowercase characters are significant.
It should not be a keyword.
It should be a meaningful name, so as to reflect its use.
Whitespace between the variables is not allowed, means a variable should be a
single word, but to join the words we can use underscore (_).
The length of a variable changes from compiler to compiler.
Valid Invalid
Name 3name
MAX @MAX
_sum -sum
Initialization of variables:
The process of assigning values to the declared variables is called variable initialization.
A variable must be initialized or assigned to a suitable value using an assignment
operator (=), otherwise some random value will be stored.
Syntax:
variable_name = value;
Ex:
num = 10;
fact = 2562;
menu = ‘x’;
avg = 75.562;
We can also combine both declaration and initialization of variables as follows:
Syntax:
datatype variable_name = value;
Ex:
int num = 10;
long fact = 2562;
char menu = ‘x’;
float avg = 75.562;
Note: More than one variable of same type can be declared and initialized, each variable
can be separated by comma.
Ex: int num=2, sum=0, fact=1;
These are the functions used to read data from the keyboard and display results on the
monitor.
These functions are classified as follows:
getch( ) putch( )
getche( ) putche( )
getchar( ) putchar( )
gets( ) puts( )
Formatted IO Functions:
Examples:
scanf(“%d”, &num);
scanf(“%d %ld %f %c”, &num, &fact, &avg, &menu);
2. The printf( ) statement:
It is a formatted output function used to display data on the monitor.
It displays all types of data values.
It requires a conversion symbol or format specifier to identify the data.
The format specifiers and variable names should be same in number.
Syntax-1:
printf(“control string”, variables_names);
Syntax-2:
printf(“format specifier”, variable_name);
Syntax-3:
printf(“format specifier [,format specifier ……….]”, variable1[,variable2,
………]);
Examples:
printf(“%d”, num); /* displays the value of num */
printf(“The value of num is: %d”, num); /* o/p: The value of num is: 25 */
Sample Programs:
1. Write a C program to display a welcome message.
Source Code:
/* Program to display welcome message */
#include<stdio.h>
void main()
{
printf(“Hello! Good Morning \n”);
printf(“Welcome to SRIT”);
}
Output:
Hello! Good Morning
Welcome to SRIT
2. Write a C program to find the sum of three integers.
Source Code:
#include<stdio.h>
void main()
{
int num1, num2, num3, sum;
num1=45;
num2=10;
num3=15;
sum=num1+num2+num3;
printf(“ The sum of %d, %d and %d is %d.” num1, num2, num3, sum);
}
Output:
The sum of 45, 10 and 15 is 70.
3. Write a C program to find the sum of three floating point values.
#include<stdio.h>
void main()
{
float num1, num2, num3, sum;
printf(“ Enter any three floating point numbers:”);
scanf(“%f %f %f”, &num1, &num2, &num3);
sum=num1+num2+num3;
printf(“ The sum of %f, %f and %f is %f” num1, num2, num3, sum);
}
Output:
Enter any three floating point numbers:
45.55
12.56
35.63
The sum of 45.550000, 12.560000 and 35.630000 is 93.740000
4. Write a C program to find the area and perimeter of a rectangle.
Source Code:
#include<stdio.h>
void main()
{
int len, wid;
int area, peri;
printf(“Enter length and width of a rectangle:”);
scanf(“%d %d”, &len, &wid);
area=len *wid;
peri=2*(len+wid);
printf(“ Area of a rectangle is: %d \n”,area);
printf(“Perimeter of a rectangle is: %d”, peri);
}
Output:
Output:
Enter any two integers:
45
85
Before Interchange: num1=45, num2=85
After Interchange: num1=85, num2=45
Output:
Enter any two integers:
45
85
Before Interchange: num1=45, num2=85
After Interchange: num1=85, num2=45
Assignment:
1. Write a C program to find the total and average of your SSC marks.
2. Write a C program to find the area and perimeter of a circle.
3. Write a C program to find the product of any two integers.
4. Write a C program to calculate and display Simple Interest using
SI=(p*t*r)/100.
5. Write a C program to convert given days into hours, minutes and seconds as
follows:
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds
Operators and Expressions
C is a rich of many operators to form various types of expressions.
Operator: It is a symbol used to represent some operation or computation.
Operand: It is a data name or data value on which operators performs operations.
Expression: The combination of operators and operands forms an expression which yields a
single value as a result.
Classification of Operators:
1. Unary Operators: These operators perform an operation on only one operand.
2. Binary operators: These operators perform an operation on two operands.
3. Ternary Operators: These operators perform an operation on three operands.
Types of Operators in C:
C supports a variety of operators as follows:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operator
Bitwise Operators
Special Operators
Arithmetic Operators:
These operators are used to perform mathematical arithmetic operations like
addition, subtraction, multiplication and division.
These are binary operators, hence requires two operands to perform operation.
These operators can only perform operation on numeric data types supported by C.
Following are the arithmetic operators with examples.
Program:
Write a C Program to perform basic arithmetic operations.
Source Code:
#include<stdio.h>
void main()
{
int num1, num2;
int sum, diff, prod, quot, rem;
printf(“Enter any two integers:”);
scanf(“%d %d”, &num1, &num2);
sum=num1+num2;
diff=num1-num2;
prod=num1*num2;
quot=num1/num2;
rem=num1%num2;
printf(“Sum=%d \n”, sum);
printf(“Difference=%d \n”, diff);
printf(“Product=%d \n”, prod);
printf(“Quotient=%d \n”, quot);
printf(“Remainder=%d \n”, rem);
}
Output:
Enter any two integers:
28
7
Sum=35
Difference=21
Product=196
Quotient=4
Remainder=0
Relational Operators:
These operators are used to compare two operands or data items or expressions and
gives relation between them. Hence they are also called as comparision operators.
These are binary operators.
The result of a relational expression is always a Boolean value ie; either true or false.
If the relation is True it returns 1, otherwise 0.
These operators are mainly used in selection and looping statements for framing
conditions.
Following table shows the list of relational operators with examples.
25>15 1 (true)
> Greater than
35>45 0 (false)
35<65 1
< Less than
45<25 0
10==10 1
== Equals to
15==10 0
25!=10 1
!= Not Equals to
25!=25 0
Program:
Write a program to illustrate relational operators.
Source Code:
#include<stdio.h>
void main()
{
printf(“25 > 15 = %d”, (25>15));
printf(“25 < 15 = %d”, (25<15));
printf(“25 >= 25 = %d”, (25<=25));
printf(“25 <= 25 = %d”,(25<=25));
printf(“25 == 25 = %d”, (25==25));
printf(“25 != 15 = %d”, (25!=15));
}
Output:
25 > 15 = 1
25 < 15 = 1
25 >= 25 = 1
25 <=25 = 1
25 == 25 = 1
25 != 15 =1
Logical Operators:
These operators are used to know the logical relationship between two Boolean
expressions.
The result of these operators is also a Boolean value. i.e; either true(1) or false(0).
These operators must be applied between two Boolean values.
Following table shows list of logical operators.
| Bitwise OR 18 | 5
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
Insert 0.
discarded
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0
Example:
1. Consider the following expression:
4.5 * 2 + 3.5 = 12.5
Here, 4.5 is floating-point value
2 is an integer
3.5 is floating-point value
According to the hierarchy shown in above figure, float is the higher type than integer,
hence 2 implicitly converted to float, then floating-point operation will be performed and
the result is also floating-point i.e; 12.5
2.
= *= += -=
<<= >>=
Assignment Operators Right to Left 14
&&= ||= &=
|= ^=
Examples:
1. Find x where x = 4/2+5*3-6+2*4
x=4/2+5*3–6+2*4
i
=2+5*3–6+2*4
ii
= 2 + 15 – 6 + 2 * 4
iii
= 2 + 15 – 6 + 8
iv
= 17 - 6 + 8
v
= 11 + 8
vi
= 19
2. Find y where y = 2 + 30/6+5*2*3+40/5+6
y = 2 + 30 / 6 + 5 * 2 * 3 + 40 / 5 + 6
= 2 + 5 + 5 *2 * 3 + 40 / 5 + 6
= 2 + 5 + 10 * 3 + 40 / 5 + 6
= 2 + 5 + 30 + 40 / 5 + 6
= 2 + 5 + 30 + 8 + 6
= 7 + 30 + 8 + 6
= 37 + 8 + 6
= 45 + 6
= 51