0% found this document useful (0 votes)
137 views

Module1 - PCD Engineering Notes

This document introduces the C programming language. C was developed in the 1970s and influenced by other languages like BCPL and B. It provides data types like integers, floats, characters, arrays, structures, and unions. C offers control structures like conditional statements and loops. Algorithms and flowcharts are presented as ways to design the logic and flow of a program before writing the actual C code. Algorithms use pseudocode to describe the steps, while flowcharts use graphical notations to represent program control and logic.

Uploaded by

Purushotham D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Module1 - PCD Engineering Notes

This document introduces the C programming language. C was developed in the 1970s and influenced by other languages like BCPL and B. It provides data types like integers, floats, characters, arrays, structures, and unions. C offers control structures like conditional statements and loops. Algorithms and flowcharts are presented as ways to design the logic and flow of a program before writing the actual C code. Algorithms use pseudocode to describe the steps, while flowcharts use graphical notations to represent program control and logic.

Uploaded by

Purushotham D
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Programming in C and Data Structures Module 1

INTRODUCTION TO C LANGUAGE

1.1 Introduction to C
 C is a general purpose programming language developed by Dennis Ritchie at AT& T Bell
laboratories in 1972.
 C is closely related to UNIX system and many of the important ideas are taken from “BCPL”(Basic
Combined Programming Language) developed by Martin Richards and “B” language.
 C provides variety of data types, derived data types like pointers, arrays, structures and unions.
 It also provides control flow constructions like conditional and looping constructs.

1.1.1 Why high level language or Why C?


 Generally computer understands only binary data i.e., 0’s and 1’s.
 Writing and understanding programs in binary was very difficult and time consuming.
 To overcome this high level language was introduced; the user feels comfortable in writing the
program.
 Many high levels languages are available like C, C++, JAVA etc..
 Even though the program is written in high level language, the code has to be converted to machine
language so that computer can execute it for which we make use of compiler.

1.1.2Advantages/Features of C Language
There are many features which attracted programmers for the usage of C. They are
1. Simple and Portable: it gives programmer access to all functions of the machine and can work on
different kinds of computers.
2. Powerful and Flexible: most of the functionalities like UNIX is written in C. The compiler and
interpreter is also written in C language.
3. Modularity: C is a structured programming language which mainly deals with the procedures. It is
also termed as procedure oriented language.
4. Efficient: C is more efficient which increases the speed of execution and management of memory
compared to low level languages.
5. Programmer oriented: It has many data types and flexible control structure which gives access to
hardware.
6. Other features include
 Machine independent
 No need to worry about machine details.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 1


Programming in C and Data Structures Module 1

1.1.3 Versions of C:
The main is ANSI C(accepted by American National Standards Institute) under which we have
 Lattice C
 Microsoft C
 Quick C
 Turbo C
 Borland C
 Small C
 Tiny C etc….

1.2 Pseudocode: A solution to Problem


 It is the first step in writing a program.
 It is written using a mixture of English and C language.
 It is a series of steps to solve a given problem
 It acts as a problem solving tool
Ex 1: Addition of two numbers Ex 2: Area of Circle
 Get the numbers[a,b] Get the radius[r]
 Compute addition [Sum= a + b] Compute area[Area = 3.141*r*r]
 Print the results [Sum] Print the results [Area]
Advantage:
 Easy to write and understand
 It is relatively easy to convert English description solution of small programs to C program.
Disadvantage:
 It is very difficult to translate the solution of lengthy and complex problem in English to C

1.3 Algorithm
 It is a step by step procedure to solve a problem
 A sequential solution of any problem that is written in human language.
 Using the algorithm the programmer then writes the actual program.
 The main use of algorithm is to help us to translate English into C.
 Algorithm consists of combination of statements of English and C, but not exactly C. It can then be
converted to C program.
 It is an outline or basic structure or logic of the problem.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 2


Programming in C and Data Structures Module 1

1.3.1 Characteristics of Algorithm


 Each and every instruction must be precise and unambiguous
 Each instruction execution time should be finite.
 There should be a termination condition.
 It has to accept 0 or more inputs and produce compulsory an output.
 It can accept any type of input and produce a corresponding output.

1.3.2 General Way of Writing the Algorithm


 Name of the algorithm must be specified.
 Beginning of algorithm must be specified as Start
 Input and output description may be included
 Step number has to be included for identification
 Each step may have explanatory note provided with in square bracket followed by operation.
 Completion of algorithm must be specified as end or Stop.

Ex 1: Write an algorithm to add two numbers Ex 2: Write an algorithm to compute simple interest
Algorithm: Addition of two numbers Algorithm: To find Simple Interest
Input: Two number a and b Input: p, t, r
Output: Sum of two numbers Output: si
` Step 1: Start Step 1: Start
Step 2: [input two number] Step 2: [input a principle p, time t and
rate r]
Read a and b Read p, t, r
Step 3: [compute its addition] Step 3: [compute simple interest]
Sum = a + b SI  (p*t*r)/100
Step 4: print Sum Step 4: display si
Step 5: Stop Step 5: Stop

1.4 Flow charts


 A flowchart is a pictorial or graphical representation of an algorithm or a program.
 It consistsequences of instructions that are carried out in an algorithm.
 The shapes represent operations.
 Arrows represent the sequence in which these operations are carried out.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 3


Programming in C and Data Structures Module 1

 It is mainly used to help the programmer to understand the logic of the program.

1.4.1 Notations used in flowchart

Shape Name Meaning


Start and Stop Used to denote start and stop of flowchart
Parallelogram used to read input and display
Input and Output
output
Rectangle used to include instructions or
Processing
processing statements
To include decision making statements rhombus
Decision/ Condition
is used
Connector Join different flow chart or flow lines
Repetition/ Loop Hexagon is used for looping constructs
To include functions in a program, the name of
Functions
function should be enclosed with in the figure

Control Flow Lines Arrows denoting flow of control in flow chart

For including the comments, definition or


Comment box
explanation

Ex 1.Algorithm and Flowchart to Input the dimensions of a rectangle and print its area

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 4


Programming in C and Data Structures Module 1

Step 1: Start
Step 2: read length, breadth
Step 3: Compute ‘area’
area=length * breadth
Step 4: display area
Step 5: Stop

Ex 2.Algorithm and Flowchart to Input the dimensions of a rectangle and print area and perimeter

Step1 :start
Step 2: read length, breadth
Step3: area  length * breadth
Step 4: Compute ‘perimeter’
Step 5: perimeter
2*(length+breadth)
Step 6: display area, perimeter
Step 7: stop

Ex 2.Input 3 numbers, and print the biggest number.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 5


Programming in C and Data Structures Module 1

Step 1: start
Step 2: input a,b,c
Step 3: if a>b
Bigaba
else
bigabb
end if

Step 4: if c>bigab
display c
else
display bigab
end if
Step 5: stop

1.4.2 Need for writing algorithm and flow charts


 Effective communication
 Effective analysis
 Effective coding
 Effective debugging
 Easy maintenance
 Proper documentation

1.4.3 Disadvantages of flow chart


 Not suitable for large program
 Time consuming
 Expensive
 Difficult to modify

1.5Structure of C Program

Comments/Documentation Section
Preprocessor Directives
Global declaration section

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 6


Programming in C and Data Structures Module 1

Void main( ) [Program Header]


{
Local Declaration part
Execution part
Statement 1
------------
------------
Statement n
}
User defined Functions

Comments/Documentation Section
 To specify the description so as to make understand the program or statements comments are used.
 The comments are not strictly necessary used in a program.
 The comment begins with /* and ends with */. The symbols /* and */ are called comment line
delimiters.
 We can put any message we want in the comments.
Example: /* Program to compute Quadratic Equation */
Note: Comments are ignored by C compiler, i.e. everything within comment delimiters

Preprocessor Directives
 Preprocessor Directives begins with a # symbol
 Provides instructions to the compiler to link functions from system library.
 A function is a building block of a program where it performs a particular task.
 Some examples of header files are
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <math.h>
#include<stdlib.h> Etc…

Global Declaration Section


 There will be some variable which has to be used in anywhere in program and used in more than one
function which will be declared as global.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 7


Programming in C and Data Structures Module 1

The Program Header


 Every program must contain a main() function. The execution always starts from main function.
 Every C program must have only one main function.

Body of the program


 Series of statements that performs specific task will be enclosed within braces { and }
 It is present immediately after program header.
It consists of two parts
1. Local Declaration part: Describes variables of program
Ex:int sum = 0;
int a , b:
float b;
2. Executable part: Task done using statements.
All statements should end with semicolon(;)

Subroutine Section: All user defined functions that are called in main function should be defined.

1.6 C Programming Concepts


 A program is a group of instructions given by the programmer to perform a specific task.
 To achieve programming there are many basic components of programming that has to be discussed
and understand the concepts.

Character set of C language


The C language includes the characters.
 Alphabets(lowercase a-z, Uppercase A-Z)
 Digits (0-9)
 Special Symbols( ~ ‘ ! @ # % & * () - + / $ = \ { } [ ] : ; “ “ ? etc)

1.7 C- Tokens
 Tokens are the smallest individual units of C program.
 A token is collection of characters.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 8


Programming in C and Data Structures Module 1

1.7.1 Keywords
 Words which have fixed meanings are called keywords.
 These are basic building blocks of C program statements.
 The meaning of keywords will be known to computer no new name or meaning can be defined for it.
 There are totally 32 keywords supported in C they are:
Auto double if static
break else int struct
case enum long switch
char extern near typedef
const float register union
continue for return unsigned
default for short void
do goto signed while

Rules for keywords


 Keywords should be written in lowercase letters.
 Keywords meaning cannot be changed by the users.
 It should not be used as variables, functions names and array names.
1.7.2 Identifiers or Variables
 These refer to names of variables, functions and arrays.
 These are user defined names and do not have fixed meaning.
 It is name given to computer memory location.

Rules for identifiers/variables


 First character must be an alphabet or an underscore(_)
 First character is followed by any number of letters or digits.
 Only first 31 characters are significant

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 9


Programming in C and Data Structures Module 1

 Keywords cannot be used


 Must not contain blank space/white space
 Must contain only alphabets, digits and one special symbol underscore
 Two successive underscore is not permitted
Ex:-
india Valid
india06 Valid
_india Valid
india_06 Valid
india_06_king Valid
_ _india not valid as it contains successive underscore
06india not valid as it starts from digits
int not valid since int is a keyword
india 06 not valid since there is space between india and 06
india@06 not valid since @ is not allowed

1.7.3 Constants
Constants refers to fixed values that do not change during the execution of a program
We have different types of constants
1. Integer constant
2. Real constant/Floating Pointing
3. Character constant Ex: ‘a’, ‘9’, ‘\n’
4. String constant Ex: “INDIA”, “8”

Integer constant:
 It refers to sequence of digits
 Embedded spaces, commas, characters should not be included.
 Must not contain a decimal point.
 May be signed or unsigned. (default is +)
Three types of integers
 Decimal integers:Consist of digits 0 to 9
Ex: 123 -345 0 5436 +79
 Octal integers: Digits from 0 to 7 but it has to start with 0

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 10


Programming in C and Data Structures Module 1

Ex: 027 0657 0777645


 Hexadecimal integers:Digits from 0 to 9 and characters from a to f, it has to start with 0X or
0x
Ex: 0X2 0x56 0X5fd 0xbdae

Real constants/Floating point:


The numbers that are represented by fractional parts are called real constants.
Two forms
1. Fractional form:
 digits from 0 to 9, sign (+ or -), dot(.)
 Ex: 0.0083 215. -71. +0.56 etc..
2. Exponential form:
 Syntax: mantissa e exponent
 Mantissa is either real number expressed in decimal notation or integer.
 Exponent is integer with optional + or –
 Ex: 0.65e4 3.18e-2 73e+3 12e+5

1.7.4 Data types and sizes


The data type defines the type of data stored in memory location or the type of data the variable can hold.
There are few basic data types supported in C. They are
 char
 int
 float
 double
 void

Character data type (char):


 capable of holding one character from the local character set.
 The size of the character variable is 1 byte.
 The range is from -128 to +127.
 Each character stored in the memory is associated with a unique value termed as ASCII (American
Standard Code for Information Interchange).
 It is used to represent character and strings.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 11


Programming in C and Data Structures Module 1

Integer data type (int):


 It stores an integer value or integer constant.
 Typically reflects the natural size of integers on host machine.
 General size is 2 bytes.
 The range is -32768 to +32767 ( To calculate the size 1 byte =8bits so 2bytes will be 16 bits then
range will be -215 to +215 -1).
 int can have additional datat type which is long int whose size will be of 4 bytes and the size ranging
from -231 to +231 -1.

Floating data type (float):


 single precision floating point.
 Holds a real constant.
 The size is 4 bytes.
 The range is -3.4e38 to +3.4e38.
 Float can hold the real constant accuracy up to 6 digits after the decimal point. That is 23.456789 is
valid where as 45.678953231 is invalid.

Double data type (double):


 Double precision point.
 Holds real constant.
 The size is 8 bytes.
 The range is from -1.7e308 to +1.7 e308.
 Double can hold real constant up to 16 digits after the decimal point.

Void data type (void):


 It is an empty data type.
 No memory is allocated.Mainly used when there are no return values.
1.7.5 Declaration of variables:
 The declaration tells the computer which storage locations or variables to use in the program.
 The variables which will be used in the program should be declared at the beginning of the program.
 The variable declaration indicates the type of constant that the variable can hold and the amount of
memory allocated to the variable.
 The name of the variables should be declared as per the rules of declaring identifiers or variables.
 General Syntax:
datatype variable;(or)

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 12


Programming in C and Data Structures Module 1

datatype variable1, variable2,……..variablen;


example: int a;
floatx,y;
double sum, midun_06;
 From the examples we will come to know that “a” is a variable of type integer and allocates 2 bytes
of memory. “x” and “y” are two variable of type float which will be allocated 4 bytes of memory for
each variable. “sum” and “midun_06” are two double type variables which will be allocated with 8
bytes of memory for each.
1.7.6 Assignment statements
 Declaration indicates only creating space for variables but doesn’t assigns any value.
 General Syntax:
Var_name = expr;
Where,
Var_name is the name of the variable ,
expr is the value of the expression.
 The “expr” on the right hand side is evaluated and stored in the variable name (Var_name) on left
hand side.
 The expression on the right hand side may be a constant, variable or a larger formula built from
simple expressions by arithmetic operators.
Examples:
 int a=10; // assigns the value 10 to the integer variable a
 float x;
x=20; // creates a variable y of float type and assigns value 20 to it.
 int a=10,b;b=a; // creates two variables a and b. “a” is assigned with value 10, the value of “a” is
assigned to variable “b”. Now the value of b will be 10.
 price = cost*3; //assigns the product of cost and 3 to price.
 Square = num*num; // assigns the product of num with num to square.
1.7.7 Displaying Output using printf
 printf is an output statement in C used to display the content on the screen.
 There are various forms of printf statements.
Way 1: printf(“ literal string”);
 Literal string may be any character or content. Whatever the content included within the double
quotes will be displayed on the output screen
 Example: printf(“Welcome to India”);

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 13


Programming in C and Data Structures Module 1

Output: Welcome to India


Way 2:printf(“ format string”, variable list);
 Format string will be the access specifier of particular data type and variable list are the variable
names separated by comma.
 Example: int a=10;
float b=20;
printf(“ integer =%d, floating=%f”,a,b);
output: interger=10, floating=20.00000
 While specifying the variables name make sure that it matches to the format specifiers with in the
double quotes.
i.e., printf(“ integer =%f, floating=%d”,a,b); is invalid and leads to error since “a” is int and “b” is
float.
printf(“ integer =%d, floating=%f”,b,a); is invalid and leads to error since “a” is int and “b” is float.

Guidelines for printf


 printf should contain control string or format string in quotes.
 Control string may or may not be followed by some variables or expressions.
 To print a value it needs convention specification or access specifier to be included.
 When printf statement is executed the convention specifier or access specifier will be replaced by its
value.
 Additional characters included between the accessspecifiers will be maintained as it is on the output
screen.

1.7.8 Format Specifiers


 Format specifiers are the character string with % sign followed with a character. It specifies the
type of data that is being processed. It is also called conversion specifier. When data is being
output or input it must be specified with identifier (variable) and their format specifier.
 There are many format specifiers defined in C. Take a look at the following list:
Symbols Meaning

%i or %d integer number

%f float point number

%c Character
%o octal number

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 14


Programming in C and Data Structures Module 1

%x hexadecimal integer(Lower case letter x)

%X hexadecimal integer(Upper case letter X)

%e floating point value with exponent(Lower case letter e)

%E floating point value with exponent (Upper case letter E)

%g floating point value with or without exponent

%ld long integer

%s String

%lf double

1.7.9 Escape sequence:

Escape sequence are special character denoted by a backslash (\) and a character after it. It is called escape
sequence because it causes an ‘escape’ from the normal way for characters are interpreted. For example if we
use ‘\ n’, then the character is not treated as n but it is treated as a new line. Some of the common escape
sequence characters are:

Escape sequence Meaning


\a bell
\ beep
\n new line
\t tab horizontal
\b move the character to left
one space
\\ backslash
\’ single quote
\” double quote

1.7.10 Inputting Values Using scanf


 To enter the input through the input devices like keyboard we make use of scanf statement.
 General Syntax: scanf(“format string”,list of address of variables);
Where: Format string consists of the access specifiers.
List of addresses of variables consist of the variable name preceded with & symbol.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 15


Programming in C and Data Structures Module 1

 Example: int a;
float b;
scanf(“%d%f”,&a,&b);
Guidelines for scanf
 No escape sequences or additional blank spaces should be specified in the format specifiers. Ex:
scanf(“%d %f”,&a,&b);//invalid
scanf(“%d\n%f”,&a,&b);//invalid
 & symbol is must to read the values, if not the entered value will not be stored in the variable
specified. Ex: scanf(“%d%f”,a,b);//invalid.

1.7.11 A Simple C Program


Example 1:Let us discuss a simple program to print the Hello RLJIT
#include<stdio.h> Output: Hello RLJIT
void main( )
{
printf(“ Hello RLJIT”);
}
This is a simple program which includes a printf statement to display the content on the screen.
Example 2:Consider another example program to find the simple interest
#include<stdio.h>
main() Output
{
intp,t,r; Simple Interest =2.000000
floatsi;
p =25;
t = 4;
r = 2;
si = (p*t*r)/100;
printf("Simple Interest=%f",si);
}
The above program illustrates the calculation of simple interest.
 Firstly we have declared the header files stdio.h for including standard input and output which will be
printf and scanf statements.
 Next we start with the main program indicated by main( )

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 16


Programming in C and Data Structures Module 1

 Within the main program we declare the required variables for calculating the simple interest. So we
declare p, t and r as int type and si as float type.
 After which we have assigned the values to p, t and r.
 Computed the simple interest by the formula (p*t*r)/100 and the result is assigned to si.
 Display the result si.

1.8Operators and Expressions

Operators:
What is an operator? An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations. Operators are used in programs to manipulate data and variables.

What is an operand?
A constant or a variable or a function which returns a value is an operand. An operator may have one or two
or three operands.
Example:a+b-c*d/e%fIn this example there are
6 operands ie a, b, c, d, e, f and 5 operators i.e +,-,*,/ and %.

What are the types of operators?

1.8.1 C operators can be classified into a number of categories based on type of operation
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

1) Arithmetic operators
C provides all basic arithmetic operators. The operators are +, - ,* , / , %.
Let a=10, b=5. Here, a and b are variables and are known as operands.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 17


Programming in C and Data Structures Module 1

Description Symbol Example Result Priority


Addition + a+b = 10 + 5 15 2

Subtraction - a-b = 10 – 5 5 2

Multiplication * a* b = 10 * 5 50 1

Division(Quotient) / a/b = 10/5 2 1

Modulus(Remiender) % a % b = 10 % 5 0 1

/*Program to illustrate the use of arithmetic operators is given below*/


#include<stdio.h>
Void main()
{
int a=30,b=5,c,d,e,f,g; Output: 35,25,150,6,0
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
printf(“%d, %d, %d ,%d ,%d\n”, c,d,e,f,g);

2) Relational Operators
We often compare two quantities depending on their relation, take certain decisions. For example, we
compare the age of two persons, or the price of two items, and so on. These comparisons can be done with
the help of relational operators.
An expression such as
a<b or 1<20
Containing a relational operator is termed as a relational expression. The value of relational expression is
either one or zero. It is one if the specified relation is true and zero if the relation is false.
Example: 10 < 20 is true.
20 < 10 is false.

C supports six relational operators in all. These operators are

Operator Meaning Priority

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 18


Programming in C and Data Structures Module 1

< is less than 1


<= is less than or equal to 1
> is greater than 1
>= is greater than or equal to 1
== is Equal to 2
!= is not equal to 2

When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will
be evaluated first and then the results compared. That is arithmetic operators have a higher priority over
relational operators.
Example: a+b>c+d
In the above example first it will perform addition operation on both sides and after words it will compare the
results.Relational expressions are used in decision statements such as if and while to decide the course of
action of a running program.

3) Logical Operators
In addition to the relational operators, C has the following three logical operators.
Operator Meaning
&& logical AND
|| logical OR
! logical NOT

The logical operators && and | | are used when we want to test more than one condition and make decisions.
An example: a>b && x==10
The above logical expression is true only if a>b is true and x==10 is true. If either (or both) of them are false,
the expression is false.

4) Assignment Operators
Assignment operators are used to assign the result of an expression to a variable. We have seen the usual
assignment operator,‟=‟. In addition, C has a set of “shorthand‟ assignment operators of the form.
v op = exp;
where v is a variable, exp is an expression and op is a C library arithmetic operator. The operator op= is
known as the shorthand assignment operator.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 19


Programming in C and Data Structures Module 1

The assignment statement


v op= exp;
is equivalent to v= v op (exp).
with v evaluated only once.

Consider an example
x + = y+1;
This is same as the statement
x = x+ (y+1);

5) Increment and Decrement Operators


C allows two very useful operators not generally found in other languages. These are the increment and
decrement operators:
++ and --
The operator ++ adds 1 to the operand, while -- subtracts 1. Both are unary operators takes the following.
++m; or m++;
--m; or m--;
++m is equivalent to m=m+1;
--m is equivalent to m=m-1;

We use increment and decrement statements in for and while loops extensively. While ++m and m++ mean
the same thing when they form the statements independently, they behave differently when they are used in
expressions on the right hand side of an assignment statement.

Consider the following


m=5;
y=++m; // In this case, the value of y and m would be 6.

Suppose, if we rewrite the above statements as


m=5;
y=m++; // Here the value of y would be 5 and m would be 6.

A prefix operand first adds 1 to the operand and then result is assigned to the variable on left. On the other
hand, a postfix operator first assigns the value to the variable on left and then increments the operand.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 20


Programming in C and Data Structures Module 1

6) Conditional Operator (OR) Ternary Operator


A ternary operator pair “? :” is available in C to construct conditional expressions of the form
exp1? exp2: exp3
where exp1,exp2, and exp3 are expressions.

The operator ?: works as follows: exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is
evaluated and 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 expressions is evaluated.
For example, consider the following statements.
a=10;
b=15;
x = (a>b)? a:b;
In this example, x will be assigned the value of b. This can be achieved using the if… else statements as
follows:
if (a>b)
x=a;
else
x=b;

7) Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be
applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Bitwise Negate

8) Special Operators
C supports some special operators of interest such as comma operator, sizeof operator.
 The Comma Operator
The comma operator can be used to link the related expressions together. A comma-linked list of expressions
are evaluated from left to right and the value of right-most expression is the value of the combined
expression.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 21


Programming in C and Data Structures Module 1

For example, the statement: value = (x=10,y=5,x+y)


first assigns the value 10 to x, then assigns 5 to y , and finally assigns 15 to value. Since comma operator has
the lowest precedence of all operators, the parentheses are necessary.
 The sizeof() Operator
The sizeof() is a compile time operator and, when used with an operand, it returns the number of bytes the
operand occupies. The operand may be a variable, or a constant or a data type qualifier.
Examples: m=sizeof(sum);
n= sizeof(5);

1.8.2 Classification Based on number of Operands


The Operators are classified into four major categories based on the number of operands as shown
below
(i) Unary Operators
(ii) Binary Operators
(iii) Ternary Operators
(iv) Special Operators
Unary Operators: An operator which acts on only one operand to produce the result is called unary
operator. The Operators precede the operand.
Examples: -10 -a --b
Binary Operators: An operator which acts on two operands to produce the result is called a binary operator.
In an expression involving a binary operator, the operator is in between two operands.
Examples: a + b a*b
Ternary Operator: An operator which acts on three operands to produce a result is called a ternary operator.
Ternary operator is also called conditional operator.
Example:a ?b : c
Since there are three operands a, b and c (hence the name ternary) that are associated with operators ?and :
it is called ternary operator.

Precedence[Priority]
It is the rule that specifies the order in which certain operations need to be performed in an
expression. For a given expression containing more than two operators, it determines which operations
should be calculated first.
Associativity

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 22


Programming in C and Data Structures Module 1

If all the operators in an expression have equal priority then the direction or order chosen left to right
or right to left to evaluate an expression is called associativity.
BODMAS Rule can be used to solve the expressions, where B: Brackets O: Operators D: Division
M: Multiplication A: Addition S: Subtraction
The Precedence (Hierarchy) of Operator
Operators in Order of
Operator Category Precedence Associativity
(Highest to Lowest)
Innermost brackets/Array (), [], {} Left to Right(L->R)
elements reference
Unary Operators ++, --, sizeof(), ~, +, - Right to Left(R->L)
Member Access -> or * L->R
Arithmetic Operators *, /, % L->R
Arithmetic Operators -, + L->R
Shift Operators <<, >> L->R
Relational Operators <, <=, >, >= L->R
Equality Operators ==, != L->R
Bitwise AND & L->R
Bitwise XOR ^ L->R
Bitwise OR | L->R
Logical AND && L->R
Logical OR || L->R
Conditional Operator ?: R->L
Assignment Operator =, +=, -=,*=, /=, %= R->L
Comma Operator , L->R

1.9 Expressions
An expression is a sequence of operands and operators that reduces to a single value. Expressions can be
simpler or complex. An operator is a syntactical token that requires an action to be taken .An operand is an
object on which an operation is performed.
We can divide simple expressions into six categories based on the number of operands, relative positions of
the operand and operator
1. Primary Expressions
2. Unary Expressions

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 23


Programming in C and Data Structures Module 1

3. Binary Expressions
4. Ternary Expressions
5. Assignment Expressions
6. Comma Expressions

1. Primary Expressions
An expression with only one operand but without any operator is called primary expression. The various
types of primary expressions are:
(i) Names Ex: int a
(ii) Constants Ex: 5, 10.5
(iii) Parenthesized expressions Ex: (2+3*(4-2))
2. Unary Expressions
An expression with only one operand and one operator is called unary expression. The unary expression act
on a single operand to produce a value. The various types of unary expressions are
(i) Unary minus expression ex: -5
(ii) Unary plus expression ex: +5
(iii) Prefix expression ex: ++i (iv) Postfix expression ex: i++
3. Binary Expressions
An expression containing two operands and an operator is called binary expression. A binary operator acts on
two operands to produce a value. The various types of binary expressions are
(i) Multiplicative expressions Ex: 2*3 , 6/2
(ii) Additive expressions Ex: a-b, a + b etc
(iii) Relational expressions Ex: a>b, a<b etc
(iv) Logical expressions Ex: a && b, a || b
(v) Bitwise expressions Ex: a &b , a | b
4. Ternary Expressions
An expression containing three operands and two operators is called ternary expression. Here, the two
operators act on three operands.
Ex: a ?b:c // a,b and c are operands and ? and :are operators
5. Assignment Expressions
A statement with assignment operator is called assignment statement. The assignment statements are often
referred to as assignment expressions
Ex 1: a=10
Ex 2: a = b + c
6. Comma Expressions

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 24


Programming in C and Data Structures Module 1

A set of statements separated by commas are evaluated from left to right one after the other. Such statements
are called statements with comma operator.
Ex: a=10, b=20, c=30;

1.10 Type Conversion


The process of converting the data from one data type to another data type is called Type conversion.
Type conversion is of two types
(i) Implicit type conversion
(ii) Explicit type conversion

i). Implicit Conversion


C permits mixing of constants and variables of different types in an expression. C automatically converts any
intermediate values to the proper type so that the expression can be evaluated without losing any
significance. The automatic conversion is known as implicit conversion.
If the Operands are of different types, the lower data type is automatically converted to higher type before the
operation proceeds.
For example,
 If one operand type is same as other operand type, no conversion takes place and type of result
remains same as the operands i.eint + int = int, float + float = float etc.
 If one operand type is int and other operand type is float, the operand with type int is promoted to
float.

Examples:
int + int = intint + float = float
5 + 3 = 8 5 + 3.5 = 8.5

ii) Explicit type conversion


Implicit type conversion is possible only if the data types of two operands are different. In some situation
where the data types of two operands are same, still conversion is required, then we have to go for explicit
type conversion.

For example, we want to find the ratio of girls to boys in the college. The ratio is given by
Ratio = no_of_girls / no_of_boys.

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 25


Programming in C and Data Structures Module 1

Here, number of girls and number of boys will be of type integer. So, the compiler will not do any
implicit type conversion because, both operands are of the same data type and hence the result will be of type
integer. But, to get the ratio which is a floating point number, we are forced to convert one of the operands to
float so that the result is also float. This is the place where we require explicit type conversion.

Definition: If the Operands are of the same data type, no conversion takes place by the compiler. Sometimes,
the type conversion is required to get the desired results. In such case, the programmer can instruct the
compiler to change the type of the operand from one data type to another data type. This forcible conversion
from one data type to another data type is called explicit type conversion.

The syntax is: (type) expression

Example: (int) 9.43


The data conversion from higher data type to lower data type is possible using explicit type conversion. The
following example gives the explicit type conversion.

x=(int) 7.5 7.5 is converted to integer by truncation

a=(int)21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5.

b=(double) sum/n Division is done in floating point mode

y=(int)(a+b) The result a + b is converted to integer

z=(int)a +b a is converted to integer and then added to b

1.10.1 Now let us see “What is type casting? Explain with example?”

Definition: C allows programmers to perform typecasting by placing the type name in parentheses and
placing this in front of the value.
For instance
main()
{

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 26


Programming in C and Data Structures Module 1

float a;
a = (float)5 / 3;
}
Gives result as 1.666666 . This is because the integer 5 is converted to floating point value before division
and the operation between float and integer results in float.

1.10.2 Evaluation of Expressions involving all the operators


The rules to be followed while evaluating any expressions are shown below.
 Replace the variables if any by their values.
 Evaluate the expressions inside the parentheses
 Rewrite the expressions with increment or decrement operator as shown below:
a) Place the pre-increment or pre-decrement expressions before the expression being evaluated and
replace each of them with corresponding variable.
b) Place the post-increment or post- decrement expressions after the expression being evaluated and
replace each of them with corresponding values.
 Evaluate each of the expression based on precedence and associativity.

IMPORTANT QUESTIONS
1. What is pseudocode? Explain with an example Dec/Jan 2015 [4M]
2. Explain the structure of C program Dec/Jan 2015 [6M/10M]
3. List out the differences between algorithm and flowchart.
4. Write a C program to find the largest of three given integer values.
5. What are the different types of operators used in C language? Dec/Jan
2015[10M]
6. Explain briefly printf() with format specifiers?
7. Write a C program to find area and perimeterof a rectangle Dec/Jan 2015 [6M]
8. With example, explain scanf() and printf() functions
9. Explain relational operators in C with example
10. Explain different unary operators in C
11. Explain any 3 bit wise operators with an example for each
12. Explain the following operators with example
a. Logical Operators
b. Relational Operators

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 27


Programming in C and Data Structures Module 1

c. Conditional Operators
13. What is type conversion? Explain types of conversion with example. Dec/Jan 2015 [6M]

14. Evaluate the expressions where a=8, b=15, c=4


i) 2*((a%5)*(4+(b-3)/(c-2)))
ii) 100/20<=10-5+100%10-20==5>=1!=20
15. List out the input and Output devices.
16. What is type casting? Explain with example?
17. Define: i) Variable ii) Constant iii) Associativity iv) Precedence Dec/Jan 2015 [8M]

Mr. Sukruth Gowda M A, Assistant Professor, Dept., of IS&E, SVIT 28

You might also like