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

CS3353C PROGRAMMING AND DATA STRUCTURES

Uploaded by

Benitta Mary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CS3353C PROGRAMMING AND DATA STRUCTURES

Uploaded by

Benitta Mary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

CS3353 C PROGRAMMING AND DATA STRUCTURES L TPC

3 0 0 3
COURSE OBJECTIVES:
 To introduce the basics of C programming language.
 To learn the concepts of advanced features of C.
 To understand the concepts of ADTs and linear data structures.
 To know the concepts of non-linear data structure and hashing.
 To familiarize the concepts of sorting and searching techniques.

UNIT I C PROGRAMMING FUNDAMENTALS (8+1 SKILL) 9


Data Types – Variables – Operations – Expressions and Statements – Conditional
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.

UNIT II C PROGRAMMING - ADVANCED FEATURES


(8+1 SKILL) 9
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays
and Functions – File Handling – Preprocessor Directives.

UNIT III LINEAR DATA STRUCTURES (8+1 SKILL) 9


Abstract Data Types (ADTs) – List ADT – Array-Based Implementation – Linked List
– Doubly- Linked Lists – Circular Linked List – Stack ADT – Implementation of Stack
– Applications – Queue ADT – Priority Queues – Queue Implementation –
Applications.

UNIT IV NON-LINEAR DATA STRUCTURES (8+1 SKILL) 9


Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree –
Hashing - Hash Functions – Separate Chaining – Open Addressing – Linear Probing–
Quadratic Probing – Double Hashing – Rehashing.

UNIT V SORTING AND SEARCHING TECHNIQUES


(8+1 SKILL) 9
Insertion Sort – Quick Sort – Heap Sort – Merge Sort –Linear Search – Binary Search.
TOTAL 45 PERIODS

UNIT I C PROGRAMMING FUNDAMENTALS (8+1 SKILL) 9


Data Types – Variables – Operations – Expressions and Statements – Conditional
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.

1. Introduction

C is a structured programming language developed by a programmer Dennis Ritchie.

• It is also called as a high level programming language.

It has small instruction set using which development of many engineering


applications is possible.

• It is a case sensitive language. That means it differentiates between the two


variables having the same letters but different cases (upper and lower case).
 In ‘C’ language each and every individual unit is called as Token or Lexical
element. The various ‘C’ Tokens are
i) Character set
ii) Delimiters
iii) Keywords
iv) Identifiers
v) Variables
vi) Constants
vii) Data types
Character Set
 The set of characters used to write the program words, expressions and
statements. It is the basic building block to form program elements. The set of
characters used in a language is known as its character set. These characters can
be represented in the computer.
 The C character set consists of upper and lower case alphabets, digits, special
characters and white spaces. The alphabets and digits are together called the
alphanumeric characters.
i) Alphabets
A, B, C,…..Z
a, b, c,….z
ii) Digits
0123456789
iii) Special Characters
Table 1.1 List of Special Characters

iv) White space characters


Blank space, newline, form feed, horizontal tab, vertical tab
v) Trigraph characters
The trigraph characters are used to type certain characters that are not
available on some keyboards. It consists of three characters. Two
question marks followed by character.

Table 1.2 Trigraph Characters


Delimiters
 The language pattern of C uses a special kind of symbols, which are called
delimiters. They are given in Table. 1.3.

Keywords:
Keywords are the standard words in C.

• These are basically the reserved words which have special meaning. The
meaning of keywords cannot be changed.
• All keywords are written in lower case.

• Various keywords used in C are listed below -

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Identifiers :
• Identifier is a collection of alphanumeric characters in which the first
character must not be numeric.

• Identifiers are the names given to the variables, functions or constants.

• The name of the identifier must not be the keyword.


Both Upper and lowercase letters can be used

Variables

• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size
and layout of the variable's memory; the range of values that can be stored
within that memory; and the set of operations that can be applied to the
variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive. There are following
basic variable types −

Type Description

• char Typically a single octet(one byte). This is an integer type.

• int The most natural size of integer for the machine.

• float A single-precision floating point value.

• double A double-precision floating point value.

• void Represents the absence of type.

• Validity of variable names


• Following are the rules which should be followed while deciding the
variable names

• 1) The first letter of the variable must not be digit or any special
character.

• 2) Special characters (such as $, #, %) are not allowed in the variable


name except underscore.

• 3) The variable name is case sensitive. A variable name can be in


capital letters.

• 4) The length of the variable name can be any but only first 31
characters are recognized.

• 5) The keywords are not valid variable names.

• 6) Blank spaces or special characters, commas, use of quotes are not


allowed in the variable name.

• 7) Arithmetic operators should not be used in the variable names.


• The variable names should be informative. It should describe the
purpose of it by its name.

• The valid variables are

• Count,tax_id,INDEX,Xyz,brick01

• The invalid variable names are

• _file,char,#id, 1A,valid name

Constants
Definition of constant: The specific alphabetical or numerical value that
never gets changed during the processing of the instructions is called
as constant.

• The constant can be alphabetical, numeric or special symbol.

• The constants are given some names and are referred by the names.

• Example: The most commonly used constant is PI. Once the value to this
constant is assigned then it does not get changed.ohcorl tugi

• The names to the constant help in accessing them easily.

• Generally all the letters in the name of the constant are capital.

Header Files
The header files contain standard library functions. For using these library
functions directly in the program, it is necessary to include the header file at
the beginning of the program.

Following are the header files supported by C


Some commonly used header files are

stdio.h: It is standard input output header file. In this file the functions
for printf, scanf, fprintf, fscanf are defined. These functions deal with input
and output functions.

conio.h: It is Console Input Output header file. In this file the typical
functions such as clrscr() is defined. By using clrscr(), the console (output)
screen gets cleared.

math.h In math.h all the functionalities related to mathematical operations are


defined. Such as pow for computing power, sqrt for computing square root
and many more.

alloc.h: This header file is used when a a function for allocating the
memory dynamically, such as malloc() is used in the program.

Key Point: We have to include header files at the beginning of C program.

1.1.Data Types
• Data types specify the type of data we enter in our program.

• In C there are some predefined set of data types which are also called
as primitive data types.

• Primitive data types are fundamental data types.

Primitive data types are fundamental data types.

(1) integer type: These data types are used to store whole number. (i.e. the
number without fraction).

Size and range of Integer type on 16-bit machine :


(2) float type : These are the data types used to store the real numbers (i.e. the
numbers with fractional part).

Size and range of Integer type on 16-bit machine

(3) char type: This data type is used to store the character value.

Size and range of Integer type on 16-bit machine


(4) void type : Void data types mean no value. This data type is normally
associated with a function that return no value.

1.2Variables and Declaration


 Variables are identifiers whose value changes during the execution of the
program. Variables specify the name and type information. The compiler
allocates memory for a particular variable based on the type.
 Variables can be modified using the variable name or address of the variable.
The variable name must be chosen in a meaningful way. The declaration of the
variable must be done before it can be used in the program.
 The general syntax of the variable declaration is given below.
datatype : var1, var2, ….,varn;
where
datatype : may be any data type
var1, var2 : variable name separated by a comma
Examples
1. int sum, count;
2. int rollno;
3. float int_rate;
4. double avg, netsal;
5. char char;
Variable declaration with qualifiers
Examples
1. short int number;
2. unsigned int total;
3. long int ser_no;
4. long double volume;
Variable Initialization
 Assigning a relevant value to a variable for the first time in a program is known
as initialization. Sometimes a variable may be initialized on its declaration itself.
Variables can be initialized with a constant value or expression.
Syntax:
datatype variablename = expression;
(or)
datatype variablename = constant;
Example
1. int c = 10, d = c + 5;
2. float rate = 12.5;
3. char ch = ‘Y’;
4. int count = 0 , sum = 0;
5. float pi = 3.14;
OPERATORS IN C
Operator: An operator is a symbol that specifies an operation to be performed on
operands. Eg: x= a+b; where + is an operator.
Operands: An operand is an entity on which an operation is to be performed. An
operand can be a variable name, a constant, a function call or a macro name.
Eg. x= a+b; where x, a, b are the operands.
Expression: An expression is a sequence of operands and operators that specifies the
computations of a value. An expression is made up of one or more operands. Eg. x=
a+b.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators (Ternary Operators)
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
 Addition, subtraction, multiplication, division and modulo are the arithmetic
operations.
 The arithmetic operators are used for numerical calculations between two
Constants
Operators Explanations Examples
+ Addition 2+2=4
- Subtraction 3-2=1
* Multiplication 5 * 4 =20
/ Division 10 / 2 = 5
% Modular Division 11 % 2 = 1

Example:
void main()
{
int a=5, b=4, c;
c=a-b;
printf(“%d”, c);
}

 Arithmetic operators can be classified as


o Unary arithmetic – it requires only one operand.
Example: +a, -b
o Binary arithmetic – it requires two operands.
Example: a+b, a-b, a/b, a%b
o Integer arithmetic – it requires both operands to be integer type for
arithmetic operation.
Example:
a=4, b=3
a+b =4+3 =7
a-b =4-3=1
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
Example:
a=6.5, b=3.5
a+b =6.5+3.5 =10.0
a-b =6.5-3.5=3.0
Program 1.3
#include<stdio.h>
#include<conio.h
> void main()
{
int b,c;
int sum, sub, mul;
float div;
clrscr();
printf(“enter the value of b,c:”);
scanf(“%d%d”, &b, &c);
sum=b+c;
sub=b-c;
mul=b*c;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=%f”,sum,sub,mul,div);
getch();
}
Output:
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=2
Relational Operators
 Relational operators are used to compare two or more operands.
 Operands may be variable, constant or expression
Operators Descriptions Example Return Value
> Greater than 5>4 1
< Less than 10<9 0
<= Less than or equal to 10<=10 1
>= Greater than or equal to 11>=5 1
== Equal to 2==3 0
!= Not equal to 3!=3 0

Syntax
AE1 operator AE2
where, AE- Arithmetic Expression or Variable or Value.
 These operators provide the relationship between two expressions.
 If the condition is true it returns a value 1, otherwise it returns 0.
 These operators are used in decision making process. They are generally used in
conditional or control statement.
Logical Operators
 Logical Operators are used to combine the result of two or more conditions.

 The logical relationship between the two expressions is checked with logical
operators.
 After checking the condition, it provides logical true (1) or false (0).
Operators Descriptions Example Return Value
&& Logical AND 5>3 && 1
5<10
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0

 && - This operator is usually used in situation where two or more expressions
must be true.
Syntax:
(exp1) && (exp2)
 || – This is used in situation, where at least one expression is true.
Syntax:
(exp1) || (exp2)
 ! – This operator reverses the value of the expression it operates on. (i.e.,) it
makes a true expression false and false expression true.
Syntax:
!(exp1)

Program 1.4
/* Program using Logical operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf("\n Condition : Return values ");
printf("\n 5<=8 && 4>2: %5d",5<=8 && 4>2);
printf("\n 5>=3 || 6<8: %5d",5>=3 || 6<8);
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values
5<=8 && 4>2 : 1
5>=3 || 6<8 : 1
!(7==7) : 0

Assignment Operator
 Assignment Operator are used to assign constant or a value of a variable or an
expression to another variable.
Syntax
variable =expression (or) value;
Example
x=10;
x=a+b;
x=y;

Program 1.5
/* Program using Assignment and Short-hand Assignment operators */
#include<stdio.h>
#include<conio.h
> void main( )
{
int a=20,b=10,c=15,d=25,e=34,x=5;
clrscr( );
printf("\n Value of a=
%d",a); printf("\n Value of
b=%d",b); a+=x;

b- =x; c*=x; d/=x; e%=x;


printf("\n Value of a=%d",a);
printf("\n Value of b=%d",b);
printf("\n Value of c=%d",c);
printf("\n Value of d=%d",d);
printf("\n Value of e=%d",e);
getch();
}

Output

Value of a = 20

Value of b = 10

Value of a = 25

Value of b = 5

Value of c = 75

Value of d = 5

Value of e = 4
Increment and Decrement Operators (Unary Operators)
 The ‘++’ adds one to the variable and ‘--‘subtracts one from the variable. These
operators are called unary operators.
Operator Meaning
++X Pre increment
--X Pre decrement
X++ Post increment
X-- Post decrement

Pre-increment operator
 These operators increment the value of a variable first and then perform
other actions.
Program 1.6
#include <stdio.h>
void main()
{
int a,b;
a=10;
b=++a;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
output: a=11 b=11
#include <stdio.h>
void main()
{
int a,b;
a=10;
b=—a; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=9

Post-increment operator
 This operator perform other actions first and then increment the value of a
variable.
Program 1.7
#include <stdio.h>
void main()
{
int a,b;
a=10;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
Output:
a=11 b=10
Conditional Operator (or) Ternary Operator
 Conditional operator checks the condition itself and executes the statement
depending on the condition.
Syntax
condition?exp1:exp2;
Example
void main()
{
int a=5,b=3,big;
big=a>b?a:b;
printf(“big is…%d”,big);
}
Output
big is…5
Bitwise Operators
 Bitwise operators are used to manipulate the data at bit level.
 It operates on integers only.
 It may not be applied to float or real.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement

Bitwise AND (&):


 This operator is represented as ‘&’ and operates on two operands of integer type.
If both the operands bit is ‘1’ then the result is ‘1’.
Bitwise OR (|):
 Bitwise OR (|) operator gives the value ‘1’ if either of the operands bit is ‘1’
Bitwise Exclusive OR (^)
 Bitwise Exclusive OR(^) gives the value ‘1’ if both operands bit are same.
Program 1.9
/* Program using One's complement operator */
#include<stdio.h>
#include<conio.h
> void main( )
{
int a;
clrscr( );
printf("\n Enter the value for a : ");
scanf("%d",&a);
printf("\n The One's complement value for a is : %d", ~a);
getch( );
}
Output
Enter the value for a: 3
The One's complement value for a is: -4
The Special Operator
 C language supports some of the special operators given below.
Operator Meaning
, Comma operators
sizeof Size of operators
& and * Pointer operators
. and — > Member selection operators

a) Comma operator(,):
 The comma operator is used to separate the statement elements such as
variables, constants or expression etc.,
 This operator is used to link the related expression together.
 Such expression can be evaluated from left to right and the value of right most
expression is the value of combined expression.
Example:
val=(a=3,b=9,c=77,a+c);
Where,
First assigns the value 3 to a
Second assigns the value 9 to b
Third assigns the value 77 to c
Last assigns the value 80.
b) The sizeof() operator:
 The sizeof() is a unary operator that returns the length in bytes of the specified
variable and it is very useful to find the bytes occupied by the specified variable
in memory.
Syntax:
sizeof(var);
Example:
void main()
{
int a;
printf(“size of variable a is…%d”, sizeof(a));
}
Output:
size of variable a is…….2
c) Pointer operator:
 & : This symbol specifies the address of the variable.
 * : This symbol specifies the value of the variable.
d) Member selection operator:
 . and — >: These symbols are used to access the elements from a structure.

EXPRESSIONS AND STATEMENTS


Expressions
 An expression represents data item such as variables, constants and are
interconnected with operators as per the syntax of the language.
 An expression is evaluated using assignment operators.
Syntax
Variable = expression;
Example: 1
x=a*b-c;
 In example 1, the expression evaluated from left to right. After the evaluation of
the expression the final value is assigned to the variable from right to left.
Example: 2
a++;
 In example 2, the value of variable a is incremented by 1, i.e, this expression is
equivalent to a = a + 1.
Statements
 A statement is an instruction given to the computer to perform an action. There
are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
Expression Statement
 An expression statement or simple statement consists of an expression followed
by a semicolon (;).
Example
a=100;
b=20;
c=a/b;
Compound Statement
 A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{
a=3;
b=10;
c=a+b;
}
Control Statement
 A single statement or a block of statements can be executed depending upon a
condition using control statements like if, if-else, etc.
Example
a=10;
if (a>5)
{
b= a+10;
}

CONDITIONAL STATEMENTS
 The conditional statement requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false.
Conditional Branching Statement
Selection Statement
 Simple If statement
 The syntax for a simple if statement is
if (expression)
{
block of statements;
}
 In this statement, if the expression is true, the block of statements are executed
otherwise false and it comes out of the if condition.

Fig. 1.7 Flowchart for an If statement


Program 1.10
/* Program to check the given numbers are equal or not */
#include<stdio.h>
#include<conio.h
> void main()
{
int m,n;
clrscr();
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m,&n);
if (m==n)
printf(“\n Two numbers are equal”);
getch();
}
Output
Ener two numbers: 10 10
Two numbers are equal.
 If –else statement
 The syntax for the if-else statement is
if(expression)
{
block of statements1;
}
else
{
block of statements2;
}

Fig. 1.8 Flowchart for the If-else statement


 In this statement, if the expression is true the block of statements1 will be
executed, otherwise the block of statements2 will be executed.

Program 1.12
/* Program to find the given number is positive or negative */
#include<stdio.h>
void main()
{
int n;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n>0)
{
printf(“\n The given number %d is positive”, n);
}
else
{
printf(“\n The given number %d is negative”, n);
}
}
Output
Enter the number : 5
The given number 5 is positive.
 Conditional Expression
 The ternary operator is used to form a conditional expression. It uses three
operands and hence it is called as a ternary operator. The syntax for a
conditional expression is:
<expression-1> ? <expression-2> : <expression-3>;
 In this method if expression-1 is true then expression-2 is evaluated, otherwise
expression-3 is evaluated.
Fig. 1.9 Flowchart for a Conditional expression
Program 1.14
/* Program to find biggest of two given numbers */
#include<stdio.h>
void main()
{
int x,y,z;
printf(“\n Enter the value of x and y:”);
scanf(“%d%d”,&x,&y);
z = ((x>y)?x:y);
printf(“The biggest value is %d”,z);
getch();
}
Output
Enter the value of x and y: 5 10
The biggest value is 10
 If-else-if statement
 The syntax for the if-else-if statement is
if(expression1)
{
statements1;
}
else if(expression2)
{
statements2;
}
else if(expression3)
{
statements3;
}
else
{
statements4;
}
 In this statement, if the expression1 is true, statements1 will be executed,
otherwise the expression2 is evaluated, if it is true then statements2 is executed,
otherwise the expression3 is evaluated, if it is true then statements3 is executed,
otherwise statements4 is executed.

Fig. 1.10 Flowchart for the If-else-if statement


Program 1.15
/* Program to find the student’s class for the given average marks using if-elseif*/
#include<stdio.h>
void main()
{
int Avg_Mark;

DOWNLOADED FROM STUCOR


printf (“Enter the Average mark:”)
scanf(“%d”,&Avg_Mark); if(Avg_Mark>=75)
{
printf(“Distinction”);
}
elseif((Avg_Mark>=60) && (Avg_Mark<75))
{
printf(“First Class”);
}
elseif((Avg_Mark>=50) && (Avg_Mark<60))
{
printf(“Second Class”);
}
elseif((Avg_Mark>=45) && (Avg_Mark<50))
{
printf(“Third Class”);
}
else
{
printf(“Fail”);
}
}
Output
Enter the Average Mark : 65
First Class

You might also like