0% found this document useful (0 votes)
78 views100 pages

Module II: Programming in C: Amity School of Engineering and Technology

The document provides an overview of the topics to be covered in the module on programming in C, including: 1. The history of C and its evolution from earlier languages like BCPL and B. 2. The basic structure of a C program and the process of compiling a C program. 3. The fundamental building blocks of a C program like variables, constants, keywords, data types and storage classes. 4. The rules for constructing integer constants, real constants and character constants in C.

Uploaded by

Akanksha Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views100 pages

Module II: Programming in C: Amity School of Engineering and Technology

The document provides an overview of the topics to be covered in the module on programming in C, including: 1. The history of C and its evolution from earlier languages like BCPL and B. 2. The basic structure of a C program and the process of compiling a C program. 3. The fundamental building blocks of a C program like variables, constants, keywords, data types and storage classes. 4. The rules for constructing integer constants, real constants and character constants in C.

Uploaded by

Akanksha Thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Amity School of Engineering and Technology

Module II: Programming in C


Topics to be covered

• History of C, Introduction of C, Basic structure of C program,


Concept of variables, constants and data types in C
• Operators and expressions: Introduction, arithmetic, relational,
Logical, Assignment, Increment and decrement operator,
Conditional, bitwise operators, Expressions, Operator
precedence and associativity
• Managing Input and output Operation, formatting I/O

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

1978 K&R C Kernighan


&Ritchie
1989 ANSI C ANSI Committee

1990 ANSI/ISO C ISO Committee

1999 C99 Standardization


Committee
4
Several Reasons to Learn ‘C’
• Nobody can learn C++ or java directly without
basics.
• C++, C# or java make use of a principle called
Object oriented programming to organize the
program.
• C is still unchallenged.
• Major parts of Popular operating systems like
windows, Unix, Linux are still written in C,
because even today nothing beats C in terms of
performance even today.
Several Reasons to Learn ‘C’
 Smartness of mobile devices like cell phones, palm
tops comes from their OS, microprocessor or
embedded program which is still written in C due to
speed of C
 Several professional games which are popular due to

their speed of execution and reaction to inputs. Many


popular gaming frameworks are still built in C
 C provides close interaction with hardware devices,

without compromising performance.


Features of C Language
 Simple
 Machine Independent or Portable
 Mid-level programming language
 Structured programming language
 Rich Library
 Memory Management
 Fast Speed
 Pointers
 Recursion
 Extensible
7
Features of C Language
• Simple
C is a simple language in the sense that it provides a structured approach (to
break the problem into parts), the rich set of library functions, data types, etc.
• Machine Independent or Portable
Unlike assembly language, c programs can be executed on different
machines with some machine specific changes. Therefore, C is a machine
independent language.
• Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop
system applications such as kernel, driver, etc. It also supports the features of a
high-level language. That is why it is known as mid-level language.

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

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 11


Process of Compiling a ‘C’ Program

12
Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
Getting Started with C
Steps in Learning English Language:

Alphabets Words Sentences Paragraphs

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

Primary Constants Secondary 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.

Example: ‘A’ , ‘I’, ‘5’, ‘=‘


Fundamental Data Types and
Storage Classes
A C language programmer must tell the system before-hand,
the type of numbers or characters he is using in his program.
These are data types. There are many data types in C
language. A C programmer must use appropriate data type as
per his requirement.

C language data types can be broadly classified as

 Primary data type


 Derived data type
 User-defined data type

26
Primary Data Types

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 27


Primary Data Type
All C Compilers accept the following fundamental data
types :
1. Integer int
2. Character char
3. Floating Point float
4. Double precision double
floating point
5. Void void

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.

Examples: 24,67 ,-3456, 789 etc.

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill


29
Floating Point Data Type
Floating point number represents a real number with 6 digits precision. Floating
point numbers are denoted by the keyword float. When the accuracy of the
floating-point number is insufficient, we can use the double to define the
number. The double is same as float but with longer precision. To extend the
precision further we can use long double which consumes 80 bits of memory
space.

Examples: 12.6785 , 34.890012 etc.

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 30


void Data Type

Using void data type, we can specify the type of a


function. It is a good practice to avoid functions that
does not return any values to the calling function.
 

31
Character Data Type

A single character can be defined as a defined as a character


type of data. Characters are usually stored in 8 bits of
internal storage. The qualifier signed or unsigned can be
explicitly applied to char. While unsigned characters have
values between 0 and 255, signed characters have values from
–128 to 127.

Examples: ‘C’ , ‘A’ etc.


Size and Range of Data Types
TYPE SIZE (Bits) Range
char or signed char 8 -128(-27) to 127(27-1)

unsigned char 8 0 to 255

int or signed int 16 -32768(-215) to 32767 (215 - 1)

unsigned int 16 0 to 65535

short int or signed short 8 -128 to 127


int
unsigned short int 8 0 to 255

long int or signed long int 32 -2147483648 to 2147483647


or long
unsigned long int 32 0 to 4294967295

float 32 3.4 e-38 to 3.4 e+38

double 64 1.7e-308 to 1.7e+308

long double 80 3.4 e-4932 to 3.4 e+4932


33
34
Declaration of Variables
Every variable used in the program should be declared to the compiler. The
declaration does two things.
 
1. Tells the compiler the variables name.
2. Specifies what type of data the variable will hold.

The general format of any declaration

datatype v1, v2, v3, ……….. vn;

Where v1, v2, v3 are variable names.


Variables are separated by commas.
A declaration statement must end with a semicolon.

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

typedef type identifier;

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:

salary dept1, dept2;


average section1, section2;

Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2
are indirectly float data type.

37
Declaring Variable as Constant

The values of some variable may be required to remain


constant through-out the program. We can do this by using
the qualifier const at the time of initialization.

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

2. static int num;


Now num variable is works as a static variable.

3. extern int num;


Now num variable is works as a global variable

4. register int num;


variable num is now stored in register.

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

Examples of arithmetic operators are


x + y , x - y , -x + y , a * b + c , -a * b

here a, b, c, x, y are known as operands. The modulus operator is a special operator in


C language which evaluates the remainder of the operands after division.
43
Example Program
.
#include<stdio.h>
void main()
{
int numb1, num2, sum, sub, mul, div, mod;
scanf (“%d %d”, &num1, &num2); //inputs the operands

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.

Let x = 14.0 and y = 4.0 then

x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50

  46
Various Arithmetic

Mixed mode arithmetic


When one of the operand is real and other is an integer and if the arithmetic
operation is carried out on these 2 operands then it is called as mixed mode
arithmetic. If any one operand is of real type then the result will always be real
thus 15/10.0 = 1.5

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.

Syntax: exp1 relational operator exp2

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.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language


such as if, while and for statements to decide the course of action of a running
program 50
Logical Operators

C has the following logical operators; they compare or


evaluate logical and relational expressions.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

51
Logical Operators

Logical AND (&&)

This operator is used to evaluate 2 conditions or expressions with relational


operators simultaneously. If both the expressions to the left and to the right
of the logical operator is true then the whole compound expression is true.
Example
 
a > b && x = = 10

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 (||)

The logical OR is used to combine 2 expressions or the


condition evaluates to true if any one of the 2 expressions is
true.

Example
 
a < m || a < n

The expression evaluates to true if any one of them is true or if


both of them are true. It evaluates to true if a is less than either
m or n and when a is less than both m and n.
53
Logical Operators…

Logical NOT (!)


The logical not operator takes single expression and evaluates
to true if the expression is false and evaluates to false if the
expression is true. In other words it just reverses the value of
the expression.

For example
 
! (x >= y)

the NOT expression evaluates to true only if the value of x


is neither greater than or equal to 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.

In addition, C has a set of shorthand assignment operators of the form.


 
Var oper = exp;

Here var is a variable, exp is an expression and oper is a C binary


arithmetic operator. The operator oper = is known as shorthand assignment
operator 55

 
Assignment Operators
Example

x + = 1 is same as x = x + 1
 
The commonly used shorthand assignment operators are as follows
Shorthand assignment operators

Statement with simple Statement with


assignment 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

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

Consider the following


 
m = 5;
y = ++m; (prefix)

In this case the value of y and m would be 6

Suppose if we rewrite the above statement as

m = 5;
y = m++; (post fix)

Then the value of y will be 5 and that of m will be 6.

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

exp1 ? exp2 : exp3

The ternary operator works as follows:

exp1 is evaluated first. If the expression is true then exp2 is


evaluated & its value becomes the value of the expression. If
exp1 is false, exp3 is evaluated and its value becomes the
value of the expression. Note that only one of the expression
is evaluated.

61
Conditional or Ternary Operator
For example

a = 10;
b = 15;
x = (a > b) ? a : b

Here x will be assigned to the value of b. The condition


follows that the expression is false therefore b is assigned to x.

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 AND

| Bitwise OR

^ Bitwise Exclusive

<< Shift left

>> Shift right

64
Special Operators

C supports some special operators of interest such as comma


operator, size of operator, pointer operators (& and *) and
member selection operators (. And ->) . The size of and the
comma operators are discussed here.

The Comma Operator

The comma operator can be used to link related expressions


together. A comma-linked list of expressions are evaluated left
to right and value of right most expression is the value of the
combined expression

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

An expression is a combination of variables constants and operators written


according to the syntax of C language. In C every expression evaluates to a
value i.e., every expression results in some value of a certain type that can be
assigned to a variable. Some examples of C expressions are shown in the
table given below.

Algebraic Expression C Expression

axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

(ab / c) a*b/c

3x2 +2x + 1 3*x*x+2*x+1

(x / y) + c x/y+c

68
Evaluation of Expression
Expressions are evaluated using an assignment statement of
the form
Variable = expression;

Variable is any valid C variable name. When the statement is


encountered, the expression is evaluated first and then
replaces the previous value of the variable on the left-hand
side. All variables used in the expression must be assigned
values before evaluation is attempted.

Example of evaluation statements are


x=a*b–c
y=b/c*a
z = a – b / c + d;
69
The following program illustrates the effect of
presence of parenthesis in expressions.

.
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

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 70


Operator Precedence and Associativity

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be


evaluated from left to right using the rules of precedence of
operators. There are two distinct priority levels of arithmetic
operators in C.

High priority * / %
Low priority + -

71
Operator Precedence and Associativity

Rules for evaluation of expression

1. First parenthesized sub expression left to right are evaluated.


2. If parenthesis are nested, the evaluation begins with the
innermost sub expression.
3. The precedence rule is applied in determining the order of
application of operators in evaluating sub expressions.
4. The associability rule is applied when two or more operators of
the same precedence level appear in the sub expression.
5. Arithmetic expressions are evaluated from left to right using
the rules of precedence.
6. When Parenthesis are used, the expressions within parenthesis
assume highest priority.

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

integer value to a floating-point variable. For ex,

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

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill

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.

C supports two types of commenting.


• // is used to comment a single statement. This is known as a line comment.
A line comment can be placed anywhere on the line and it does not require
to be specifically ended as the end of the line automatically ends the line.
• /* is used to comment multiple statements. A /* is ended with */ and all
statements that lie within these characters are commented.

77
Example Programs of Integer arithmetic

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 78


USE of Shorthand operator

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill


79
Examples Program of arithmetic operators

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 80


Examples program for evaluation of expressions

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 81


Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
82
THE PRINTF() FUNCTION
• The printf function is used to display information required to the user and also prints the values of the
variables. Its syntax can be given as
printf (“conversion string”, variable list);
• The parameter control string is a C string that contains the text that has to be written on to the standard
output device. The prototype of the control string can be given as below
%[flags][width][.precision][length]specifier

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

Source: Programming in C, Reema Thareja, Oxford University Press


THE PRINTF() FUNCTION
length Description

h When the argument is a short int or unsigned short int.

When the argument is a long int or unsigned long int for


l
integer specifiers.
When the argument is a long double (used for floating point
L
specifiers)

specifier Qualifying Input


c For single character
d For decimal values
F For floating point numbers
E, e Floating point numbers in exponential format
G, G Floating point numbers in the shorter of e format
o For Octal number.
s For a sequence of (string of) characters
u For Unsigned decimal value
x ,X For Hexadecimal value.

Source: Programming in C, Reema Thareja, Oxford University Press


THE SCANF() FUNCTION
• The scanf() is used to read formatted data from the keyboard. The
syntax of the scanf() can be given as,
scanf (“control string”, arg1, arg2, ………….argn);
• The control string specifies the type and format of the data that must
be obtained from the keyboard and stored in the memory locations
pointed by the arguments arg1, arg2,…, argn. The prototype of the
control string can be given as:
[=%[*][width][modifiers]type=]
• * is an optional argument that suppresses assignment of the input
field. That is, it indicates that data should be read from the stream but
ignored (not stored in the memory location).
Source: Programming in C, Reema Thareja, Oxford University Press
THE SCANF() FUNCTION

• width is an optional argument that specifies the maximum


number of characters to be read.
• modifiers is an optional argument that can be h, l or L for
the data pointed by the corresponding additional arguments.
Modifier h is used for short int or unsigned short int, l is
used for long int, unsigned long int or double values.
Finally, L is used long double data values.
• Type is same as specifier in printf()

Source: Programming in C, Reema Thareja, Oxford University Press


Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
87
Output of Integer Numbers
• The format specification for printing an
integer number is
%w d
Where w specifies the minimum field width
for the output
Also d specifies that the value to be printed
as integer. By default, number is right
justified.

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

Here (-) and (0) are known as flags

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

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill

93
Formatted Output of Real Numbers

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill

94
Formatted Output of Character
Numbers

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill


95
Program for series 1+1/2+1/3+1/4+…………………+1/10

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 96


Program to solve a quadratic equations

Source: Programming in ANSI C, E. Balagurusamy. McGrawHill 97


Source: Programming in ANSI C, E. Balagurusamy. McGrawHill
98
References
 ANSI 89 – American National Standards Institute, American
National Standard for Information Systems Programming
Language C, 1989.
 Kernighan 78 – B. W. Kernighan and D. M. Ritchie, The C
Programming Language, Prentice-Hall: Englewood Cliffs, NJ,
1978. Second edition, 1988.
 Thinking 90 – C* Programming Guide, Thinking Machines
Corp. Cambridge Mass., 1990.
 Programming in ANSI C, E. Balagurusamy. McGrawHill
 Let Us C, Yashvant Kanetkar, BPB Publications
 Programming in C, Reema Thareja, Oxford University Press

99
Thank You

You might also like