Module II: Programming in C: Amity School of Engineering and Technology
Module II: Programming in C: Amity School of Engineering and Technology
2
History of C…..
• ALGOL was first computer language to use a block
structure developed in 1960. It gave concept of
structured programming.
• In 1967, Martin Richards developed a language,
BCPL (Basic Combined Programming Language)
• In 1970, Ken Thompson created a language called as
‘B’. It used to create early version of Unix.
• In 1972, Dennis Ritchie developed new language
called as ‘C’ at AT & T’s Bell laboratories of USA.
3
History of C…..
1972 Traditional C Dennis Ritchie
8
Features of C Language
Structured programming language
C is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.
Functions also provide code reusability.
Rich Library
C provides a lot of inbuilt functions that make the development fast.
Memory Management
It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.
9
Features of C Language
Fast Speed
The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead.
Pointers
C provides the feature of pointers. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures, functions,
array, etc.
Recursion
In C, we can call the function within the function. It provides code reusability
for every function. Recursion enables us to use the approach of backtracking.
Extensible
C language is extensible because it can easily adopt new features.
10
Basic Structure of a ‘C’ Program
12
Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
Getting Started with C
Steps in Learning English Language:
Steps in Learning C:
Alphabets
Constants,
Digits,
Variables, Instructions program
Special
Keywords
Symbols
‘C’ character Set:
Symbols
Alphabets A, B, ………………………..Y, Z
a, b, c, ……………………………y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special ~`!@#$%^&*()_-+=|\{}
Symbols [ ] : ; ” ’< > , . ? /
Constants, Variables and Keywords
• Constant is an entity that doesn’t change
• whereas a Variable is an entity that may change.
• Keywords are the words whose meaning has
already been explained to C compiler
‘C’ Variables
• An entity that may vary during program
execution is called a variable.
• Variable name are names given to locations in
memory
• These locations can contain integer, real or
character constants.
• Types of variables supported depends on type of
constant that it handles.
Rules for Constructing Variable Names:
• A variable name is any combination of 1 to 31
alphabets, digits or underscores
• The first character in the variable name must be an
alphabet or underscore.
• No comma or blanks are allowed within a variable
name
• No special symbol other than an underscore ( as in
gross_salary) can be used in a variable name.
Example: si_int
m_hra
pop_e_89
C Keywords
• Keywords are the words whose meaning has
already been explained to C compiler
• The keywords can not be used as variable names
because we cannot assign new meaning to a
keyword.
• These are also known as reserved words
• There are only 32 keywords available in C.
C Keywords
auto double int switch
break else long struct
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
‘C’ Constants:
C Constants
Array
Integer Constant Pointer
Real Constant Structure
Character Constant Union
Enum, etc
Rules for Constructing Integer
Constants:
• An Integer constant must have at least one digit.
• It must not have a decimal point.
• It can be either positive or negative
• If no sign precedes an integer constant, it is assumed
to be positive
• No Comma or blanks are allowed within integer
constant
• The allowable range for integer constants is -32768 to
32767.
Real Constants
• Real constants are often called floating point
constants.
• Real constants can be written in two forms:
• Fractional form
• Exponential form
3.2e12
Mantissa Exponent
Rules for constructing Real
constants: (in Fractional form)
• A real constant must have at least one digit.
• It must have a decimal point
• It could be either positive or negative
• Default sign is positive
• No commas or blank is allowed within a real
constant.
Example: +325.34
426.0
-32.76
-48.5792
Rules for constructing Real
constants: (in Exponential form)
• The mantissa part and the exponential part should be separated
by a letter e
• The mantissa part may have a positive or negative sign.
• Default sign of mantissa part is positive
• The exponent must have at least one digit, which must be
positive or negative, Default sign is positive
• Range of real constants is -3.4e38 to 3.4e38
Example: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Rules for Constructing Character
Constants
• A character constant is a single alphabet, a single
digit or a single special symbol enclosed within
single inverted comma
• The maximum length of a character constant can
be 1 character.
26
Primary Data Types
The size and range of each data type is given in the table
below: DATA TYPE Range Of Values
char -128 to 127
Int -32768(-215) to +32767 (215 - 1 )
float 3.4 e-38 to 3.4 e+38
double 1.7 e-308 to 1.7 e+308
28
Integer Data Type
Integers are whole numbers with a machine dependent range of values. A good
programming language as to support the programmer by giving a control on a range of
numbers and storage space. C has 3 classes of integer storage namely short int, int and
long int. All these data types have signed and unsigned forms. A short int requires half the
space than normal integer values. Unsigned numbers are always positive and consume all
the bits for the magnitude of the number. The long and unsigned integers are used to
declare a longer range of values.
31
Character Data Type
Example:
int sum;
int number, salary;
double average, mean;
35
Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
36
User defined type declaration
In C language a user can define an identifier that represents an existing data type. The user
defined data type identifier can later be used to declare variables. The general syntax is
here type represents existing data type and ‘identifier’ refers to the ‘row’ name given to the
data type.
Example:
typedef int salary;
typedef float average;
Here salary symbolizes int and average symbolizes float. They can be later used to declare
variables as follows:
Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2
are indirectly float data type.
37
Declaring Variable as Constant
Example:
Const int size = 40;
The const data type qualifier tells the compiler that the value
of the int variable size may not be modified in the program.
38
Storage Class
Variables in C have not only the data type but also storage class that provides
information about their location and visibility. The storage class divides the
portion of the program within which the variables are recognized.
auto
It is a local variable known only to the function in which it is declared. Auto is
the default storage class. Variables declared in this class are stored in RAM. This
is the default storage class, and the keyword auto is used to declare variables. Auto
variables are active in a block in which they are declared.
static
Local variable which exists and retains its value even after the control is
transferred to the calling function. Static variables in a function are initialized only
once during the compilation. Static variables are commonly used along with
functions. Static variables are automatically initialized to zero.
39
Storage Class
extern
Global variable known to all functions in the file. The global variables are
declared outside the main() function. Extern can be used to consider a local
variable in a block as a global variable. Extern variable is automatically initialized
to zero.
register
variables declared using this class are stored in the CPU memory register. Register
variables contain undefined values or garbage values unless they are initialized
explicitly. These are local variables which are stored in register.
40
Examples of Storage Class
:
1. auto int num;
or
int num;
Because auto storage class is by default
41
Operators
An operator is a symbol which helps the user to command
the computer to do a certain mathematical or logical
manipulations. Operators are used in C language program to
operate on data and variables. C has a rich set of operators
which can be classified as :
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
42
Arithmetic Operators
All the basic arithmetic operations can be carried out in C. All the operators have
almost the same meaning as in other languages. Both unary and binary operations are
available in C language. Unary operations operate on a singe operand, therefore the
number 5 when operated by unary – will have the value –5.
Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
sum = num1+num2;
printf(“\n The sum is = %d”, sum);
sub = num1-num2;
printf(“\n The difference is = %d”, sub);
mul = num1*num2;
printf(“\n The product is = %d”, mul);
div = num1/num2;
printf(“\n The division is = %d”, div);
mod = num1%num2;
printf(“\n The modulus is = %d”, mod);
}
.
44
Various Arithmetic
Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers
than such an operation is called as integer arithmetic. It always gives an integer
as the result. Let x = 27 and y = 5 be 2 integer numbers. Then the integer
operation leads to the following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
In integer division the fractional part is truncated.
45
Various Arithmetic
Floating point arithmetic
When an arithmetic operation is preformed on two real numbers or
fraction numbers such an operation is called floating point arithmetic. The
floating-point results can be truncated according to the properties
requirement. The remainder operator is not applicable for floating point
arithmetic operands.
x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50
46
Various Arithmetic
47
Problem
• Write a program to find the area of triangle. Area =
sqrt(s*(s-a)*(s-b)*(s-c))
• Write a ‘C’ program to swap two numbers with the
help of third variable:
• Write a ‘C’ program to swap two numbers without
using third Variable:
48
Relational Operators
Often it is required to compare the relationship between operands and bring out a
decision and program accordingly. This is when the relational operator come into
picture. C supports the following relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
49
Relational Operators
It is required to compare the marks of 2 students, salary of 2 persons, we can
compare them using relational operators.
A simple relational expression contains only one relational operator and takes
the following form.
Where exp1 and exp2 are expressions, which may be simple constants,
variables or combination of them. Given below is a list of examples of
relational expressions and evaluated values.
Operator Meaning
|| Logical OR
! Logical NOT
51
Logical Operators
The expression to the left is a > b and that on the right is x == 10 the whole
expression is true only if both expressions are true i.e., if a is greater than b
and x is equal to 10.
52
Logical Operators…
Logical OR (||)
Example
a < m || a < n
For example
! (x >= y)
54
Assignment Operators
The Assignment Operator evaluates an expression on the right of the
expression and substitutes it to the value or variable on the left of the
expression.
Example
x=a+b
Here the value of a + b is evaluated and substituted to the variable x.
Assignment Operators
Example
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows
Shorthand assignment operators
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b
56
EXAMPLE PROGRAM
#include<stdio.h>
main()
{
int a;
int A=2, N=100;
a = A;
while (a < N)
{
printf(“%d \n”,a);
a *= a;
}
}
.
Output
2
4
16
--
57
--
Unary Operator
• These operators are working on single operands.
• C language supports three unary operators such as
– Unary minus operator
– Increment operator
– Decrement operator
58
Increment and Decrement Operators
The increment and decrement operators are one of the unary operators which are very
useful in C language. They are extensively used in for and while loops. The syntax of
the operators is given below
1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –
The increment operator ++ adds the value 1 to the current value of operand and the
decrement operator – – subtracts the value 1 from the current value of operand. +
+variable name and variable name++ mean the same thing when they form statements
independently, they behave differently when they are used in expression on the right
hand side of an assignment statement.
59
Increment and Decrement Operators
m = 5;
y = m++; (post fix)
A prefix operator first adds 1 to the operand and then the result is assigned
to the variable on the left. On the other hand, a postfix operator first assigns
the value to the variable on the left and then increments the operand.
60
Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question
mark (?) and the colon (:)
The syntax for a ternary operator is as follows
61
Conditional or Ternary Operator
For example
a = 10;
b = 15;
x = (a > b) ? a : b
62
EXAMPLE PROGRAM
.
/* Example : to find the maximum value using conditional
operator)
#include<stdio.h>
void main()
{
int i,j,larger;
printf (“Input 2 integers : ”);
scanf(“%d %d”,&i, &j);
larger = (i > j) ? i : j;
printf(“The largest of two numbers is %d \n”, larger);
}
.
Output
Input 2 integers : 34 45
The largest of two numbers is 45 63
Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for
manipulation data at bit level. A bitwise operator operates on each bit of data. Those
operators are used for testing, complementing or shifting bits to the right on left.
Bitwise operators may not be applied to a float or double
Operator Meaning
| Bitwise OR
^ Bitwise Exclusive
64
Special Operators
65
Special Operators
For example, the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since
comma has the lowest precedence in operators the parenthesis is necessary.
Some examples of comma operator are
In for loops:
for (n=1, m=10, n <=m; n++,m++)
In while loops
While (c=getchar(), c != ‘10’)
Exchanging values 66
t = x, x = y, y = t;
The sizeof Operator
The operator sizeof gives the size of the data type or variable
in terms of bytes occupied in the memory. The operand may
be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths
of arrays and structures when their sizes are not known to the
programmer. It is also used to allocate memory space
dynamically to variables during the execution of the program.
67
Expression: Arithmetic Expressions
axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
(x / y) + c x/y+c
68
Evaluation of Expression
Expressions are evaluated using an assignment statement of
the form
Variable = expression;
.
main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %fn”,x);
printf (“y = %fn”,y);
printf (“z = %fn”,z);
}
.
output
x = 10.00
y = 7.00
z = 4.00
High priority * / %
Low priority + -
71
Operator Precedence and Associativity
72
Operator precedence and associativity
Order Category Operator Operation Associativity
1 Highest precedence () Function call L→R
[] Left to Right
→
::
.
2 Unary ! Logical negation (NOT) R→L
~ Bitwise 1’s complement Right -> Left
+ Unary plus
- Unary minus
++ Pre or post increment
-- Pre or post decrement
& Address
* Indirection
Size of Size of operant in bytes
3 Member Access .* Dereference L→R
→* Dereference
4 Multiplication * Multiply L→R
/ Divide
% Modulus
5 Additive + Binary Plus L→R
- Binary Minus
6 Shift << Shift Left L→R
>> Shift Right
7 Relational < Less than L→R
<= Less than or equal to
> Greater than
>= Greater than or equal to
8 Equality == Equal to L→R
!= Not Equal to
9 Bitwise AAND & Bitwise AND L→R
10 Bitwise XOR ^ Bitwise XOR L→R
11 Bitwise OR | Bitwise OR L→R
12 Logical AND && Logical AND L→R
14 Conditional ?: Ternary Operator R→L
15 Assignment = Assignment R L
*= Assign product
%= Assign reminder
/= Assign quotient
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
TYPE CONVERSION AND TYPE CASTING
• Type conversion and type casting of variables refers to changing a variable
of one data type into another.
• While type conversion is done implicitly, casting must be done explicitly
by the programmer. We will discuss both here.
• Type conversion is done when the expression has variables of different
data types. So to evaluate the expression, the data type is promoted from
lower to higher level where the hierarchy of data types can be given as:
double, float, long, int, short and char.
• For example, type conversion is automatically done when we assign an
float x;
int y = 3;
x = y;
Now, x = 3.0,
74
TYPE CONVERSION AND TYPE CASTING
• Type casting is considered as forced conversion. In the case, when the
value of a higher data type has to be converted into the value of a lower
data type, type casting is applied.
• For example, we need to explicitly type cast an integer variable(y) into a
floating-point variable (x).
float x = 1000.00;
int y;
y = (int) x;
• Typecasting can be done by placing the destination data type in parentheses
followed by the variable name that has to be converted.
75
Implicit Type Conversion
76
Comments
• It is a good programming practice to place some comments in the code to
help the reader understand the code clearly.
• Comments are just a way of explaining what a program does. It is merely
an internal program documentation.
• The compiler ignores the comments when forming the object file. This
means that the comments are non-executable statements.
77
Example Programs of Integer arithmetic
flag description
Left-justify within the data given field
-
width
Displays the data with its numeric sign
+
(either + or -)
Used to provide additional specifiers
like o, x, X, 0, 0x or 0X for octal and
#
hexa decimal values respectively for
values different than zero.
The number is left-padded with zeroes
0
(0) instead of spaces
88
Output of Integer Numbers
Format
printf(“%d”,1234) 1 2 3 4
printf(“%2d”,1234) 1 2 3 4
printf(“%6d”,1234) 1 2 3 4
printf(“%-6d”,1234) 1 2 3 4
printf(“%06d”,1234)
0 0 1 2 3 4
89
Output of Real Numbers
• The format specification for printing a Real
number is
%w.p f
Where w specifies the minimum field width for the output
and p indicates the number of digits to be displayed after
the decimal point. Default precision is 6 decimal places.
Also f specifies that the value to be printed as real number.
By default, number is right justified.
90
Output of Real Numbers
y= 12.3456
Format Output
printf(“%7.4f”,y) 1 2 . 3 4 5 6
printf(“%7.2f”,y) 1 2 . 3 4
printf(“%-7.2f”,y) 1 2 . 3 4
printf(“%f”,y) 1 2 . 3 4 5 6
91
Output of Single Character
• The format specification for printing a
single character is
%wc
The character will be displayed right justified in the field of
w columns. Display can be made justified by placing a
minus sign before the integer w.
By default, the value of 2 is considered as 1
92
Formatted output of integers
93
Formatted Output of Real Numbers
94
Formatted Output of Character
Numbers
99
Thank You