UNIT 1 NOTES
UNIT 1 NOTES
ODD SEMESTER
SUBJECTCODE: CS3353
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.
TOTAL 45 PERIODS
UNIT I -C PROGRAMMING FUNDAMENTALS
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
DELIMITERS
The language pattern of C uses a special kind of symbols, which are called
delimiters.
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.
IDENTIFIERS:
• Identifier is a collection of alphanumeric characters in which the first character must
not be numeric.
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
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.
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.
6) Blank spaces or special characters, commas, use of quotes are not allowed in
the variable name.
Count,tax_id,INDEX,Xyz,brick01
• 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
• 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.
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.
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.
(1) Integer type: These data types are used to store whole number. (i.e. the number without
fraction).
(3) char type: This data type is used to store the character value.
(4) void type : Void data types mean no value. This data type is normally associated with a
function that return no value.
1.3.OPERATIONS
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.
1.3.1.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
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.
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
Example Program:
#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
1.3.1.2 RELATIONAL OPERATORS
Relational operators are used to compare two or more operands.
Operands may be variable, constant or expression
Synta
x 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.
1.3.1.3 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)
Example Program
/* 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
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement
Example Program
/* 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
Example
a=10;
if (a>5)
{
b= a+10;
}
1.5.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.
1.5.1. CONDITIONAL BRANCHING STATEMENT
1.5.1.1 SELECTION STATEMENT
Simple If statement
The syntax for a simple if statement is
if (expression)
{
block of statements;
}
Switch()Case Statement
The switch() case statement is like if statement that allows us to make a decision
from a number of choices. The switch statement requires only one argument of
any data type, which is checked with a number of case options.
The switch statement evaluates the expression and then looks for its value
among the case constants.
If the value matches with a case constant, this particular case statement is
executed. If not, the default is executed. The general syntax for the switch - case
statement is:
switch<exprn>
{
case constant_1:
{
statements1;
break;
}
case constant_2:
{
statements2;
break;
}
case constant_3:
{
statements3;
break;
}
case constant_n:
{
statementsn;
break;
}
default:
{
defaultstatements;
}
}
Example Program
/*Program to Generate the Even numbers to a given limit*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf(“\nEnterthelimit:”);
scanf(“%d”,&n);
i=1;
while(i<=n)
{ if(i
%2==0)
printf(“%d\t”,i);
i++;
}
getch();
}
Output
Enter the limit: 10
2 4 6 8 10
Do While Statement
The do while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been executed
once. If the condition is false, after the first loop iteration the loop terminates.
The statements are executed at least once even if the condition fails for the first
time itself. It is otherwise called as exit control loop.
1.6. FUNCTIONS
Introduction
A function is a sub program which contains a set of instructions that are used to
perform specified tasks
A function is used to provide modularity to the software. By using function can
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.
Advantages of Functions
Code reusability
Better readability
Reduction in code redundancy
Easy to debug &test.
Types of Functions
Functions are classified into two types
a) User defined functions
b) Pre defined functions or Library functions or Built-in functions
a) User-defined functions
User-defined functions are defined by the user at the time of writing a program.
Example: sum(),square()
b) Library functions [Built-in functions]
Library functions are predefined functions.These functions are already
developed by someone and are available to the user for use.
Example: printf(), scanf( )
Function prototype
User Defined Function
The function defined by the users according to the irrequirements is called
user defined functions. The users can modify the function according to their
requirement.
Function Declaration
A function declaration is defined as a prototype of a function which consists
of the functions return type, function name and arguments list
It is always terminated with semicolon(;)
Function prototypes can be classified into four types
a) Function with no arguments and no return values
b) Function with arguments and no return values
c) Function with arguments and with return values
d) Function with no arguments and withr eturn values
Syntax
return_type function_name (parameter_list);
Where,
return_type can be primitive or non-primitive data type
function_name can be any user specified name
parameter_list can consist of any number of parameter of any type
Example
Void add(void);
Void add(int,int);
int add(int,int);
int add(void);
a) Function with No Arguments and No Return Values
In this prototype, no data transfer takes place between the calling function and
the called function.(i.e) the called program does not receive any data from the
calling program and does not send back any value to the calling program.
Syntax:
Void
function_name(void);
void main()
{
…….
function_name();
…..
}
Void function_name(void)
{
…..
……
}
b) Function with Arguments and No Return Values
In this prototype,data is transferred from calling function to called function.i.e
the called program receives some data from the calling program and does not
send back any values to calling program.
Syntax:
Void function_name(arguments_list);
void main()
{
…….
function_name(argument_list);
…..
}
Void function_name(arguments_list)
{
//function body
}
c) Function with arguments and With Return Values
In this prototype,data is transferred between calling function and called function.
( i.e)the called program receives some data from the calling program and send
back a return value to the calling program.
Value received from a function can be further used in rest of the program.
Syntax:
return_type function_name(arguments_list);
void main()
{
…….
variable_name=function_name(argument_list);
…..
}
return_type function_name(arguments_list)
{
//function body
}
1.7. RECURSIVE FUNCTIONS
Recursion is the process of calling the same function again and again until some
condition is satisfied.
This process is used for repetitive computation.
Syntax:
function_name()
{
function_name();
}
Types of Recursion
a) Direct Recursion
b) Indirect Recursion
a) Direct Recursion
A function is directly recursive if it calls
itself. Function name1( )
{
….
Function name1(); //call to itself
….
}
Example
A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a
directly recursive function.
int Func(int n)
{
if(n==0)
return n;
else
return(Func (n–1));
}
b) Indirect Recursion
Function calls another function,which in turn calls the original function.
Functionname1 ( )
{
…
Functionname2();
…
}
Functionname1()
{
…
Functionname1();//function(Functionname2)calls(Functionname1)
…
}
Example
A function is said to be indirectly recursive if it contains a call to another
function which ultimately calls it.These two functions are indirectly recursive as
they both call each other.
/*C program to find factorial of a given number using recursion*/
#include<stdio.h>
#include<conio.h>
void main()
{
intfact(int);
int num,f;
clrscr();
printf(“enter the number”);
scanf(“%d”,& num);
f=fact(num);
printf(“the factorial of%d=%d”, num,f);
}
intfact(int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(x-1);//recursive function call
return (f);
}
Output:
Enter the number 5
The factorial of 5=120
1.8 ARRAYS
1.8.1 Introduction to Arrays
An Array is a collection of similar data elements
These data elements have the same datatype
Definition
An array is a data structure that is used to store data of the same type.The
position of an element is specified with an integer value known as index or
subscript.
Example
Array Structure
Type name[size]
The values are written with curly brackets and every value is separated by a
comma. It is a compiler error to specify more number of values than the number of
elements in the array.
Example:int marks [5]={90, 92,78, 82, 58};
Example
int a[4]; // a is an array of 4 integers
char b[6]; //bisanarrayof6characters
Initialization of single dimensional array
Elements of an array can also be initialized.After declaration,the array elements
must be initialized otherwise they hold garbage value.An array can be initialized
at compile time or at run time.
Elements of an array can be initialized by using an initialization list. An
initialization list is a comma separated list of initializers enclosed within braces.
Character arrays that hold strings allow a shortcut initialization of the form:
Char array_name[size]=”string”
For example,
Char mess[]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};
Program1.33
/*Program for reversing an array*/
#include<stdio.h>
void main( )
{
Int a[10],i;
int n;
printf(“Enter the maximum number of elements\n”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Array in the reverse order\n”); for(i=n–1;
i>=0; i--)
{
printf(“%d\t”, a[i]);
}
getch();
}
1.10 MULTI-DIMENSIONAL ARRAY
A multi-dimensional array is an array that has more than one dimension. It is an
array of arrays;an array that has multiple levels.The simplest multi-dimensional
array is the 2D array,or two-dimensional array and 3D or three-dimensional
array.
Example
1 2 3 6 7
9 10 5 0 4
a[3][5] 3 1 2 1 6
Declaration
Data type array name[row size][column size]
a 1 4 6
2 0 0
}
}
/*Program module to sum col wise*/
for(i=0;i<n;i++)
{
Col sum=0;
for(j=0;j<n1;j++)
col sum+=a[j][i];
printf(“col no=%d sum=%d\n “,i,col sum);
}
/*Program module to sum principle diagonal* /
Dia sum=0; for(i=0;i<n;i+
+) for(j=0;j<n1;j++)
if(i==j)dia sum+=a[i][j];
printf(“Principle diagonal sum %d\n”,dia sum);
/* Program module to sumoff diagonal */
Dia sum=0; for(i=0;i<n;i+
+)
{
j= -n1;
Dias um +=a[i][j];
}
printf(“Off diagonal sum%d\n”,dia sum);
}
Output
Enter order[row][col]of the matrix
33
Enter9 elements
123456789
Sum of all elements45
row no = 0 sum = 6
row no = 1 sum = 15
row no = 2 sum = 24
col no = 0 sum = 12
col no = 1 sum = 15
col no = 2 sum = 18
Principle diagonal sum15
Off diagonal sum 15