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

UNIT 1 NOTES

Uploaded by

Benitta Mary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

UNIT 1 NOTES

Uploaded by

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

ACADEMIC YEAR (2024-2025)

ODD SEMESTER

DEPARTMENT OF COMPUTING TECHNOLOGIES

SUBJECTCODE: CS3353

YEAR/SEMESTER: II/III EEE

SUBJECT TITLE: C PROGRAMMING AND DATASTRUCTURE

CS3353 C PROGRAMMING AND DATA STRUCTURES

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

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.
Trigraph 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.

• 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

Typically a single octet(one byte). This


char
is an integer type.
The most natural size of integer for the
int
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

Header Description Functions/macros/variables


Files
stdio.h Input/Output functions scanf(), printf(), fopen(), FILE
stdlib.h General utility functions atoi(), atof(), malloc()
math.h Mathematics functions sin(), cos(), pow(), sqrt()
string.h String functions strcpy(), strlen(), strcat()
ctype.h Character handling functions isalpha(), isupper(), ispunct()
time.h Date and time functions asctime(), gmtime(), mktime()
float.h Limits of float types FLT_ROUNDS, FLT_RADIX,
limits.h Size of basic types CHAR_BIT, CHAR_MIN,
CHAR_MAX

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 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;

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

1.3.1.1 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.
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

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

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

1.3.1.4 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;
Example Program
/* 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();
}

1.3.1.5 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.
Example Program
#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.
Example Program
#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

1.3.1.6 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

1.3.1.7 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.

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

1.3.1.8 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.

1.4. EXPRESSIONS AND STATEMENTS


1.4.1. 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.
1.4.2. 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
4.
1.4.2.1. EXPRESSION STATEMENT
 An expression statement or simple statement consists of an expression
followed by a semicolon (;).
Example
a=100
;
b=20;
c=a/b;
1.4.2.2. COMPOUND STATEMENT
 A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Exampl
e
{
a=3;
b=10
;
c=a+b;
}
1.4.2.3. 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;
}
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;
}

Flowchart for an If statement


 In this statement, if the expression is true, the block of statements are
executed otherwise false and it comes out of the if condition.
Example Program
/* 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
Enter 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;}

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.
Example Program
/* 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.

Flowchart for a Conditional expression


Example Program
/* 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.

Flowchart for the If-else-if statement


Example Program
/* Program to find the student’s class for the given average marks using if-else if*/
#include<stdio.h>
void main()
{
int Avg_Mark;
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
 Nested if statement
 The syntax for the nested if statement is
if(expression1)
{
statements1;
}
else
{
if(expression2)
{
statements2;
}
else
{
statements3;
}
}

Flow chart for Nested if statement


 In this statement, if expression1 is true, then statement1 is evaluated, otherwise
the inner if expression2 is true then statements 2 will be executed otherwise
inner else statements3 will be executed.
/* Program to find the biggest of given three numbers */
#include<stdio.h>
void main()
{
int x,y,z;
printf(“\nEnter the three numbers”); scanf(“%d%d
%d”,&x,&y,&z);
if((x>y)&&(x>z))
{
printf(“The Biggest number=%d”,x);
}
else
{
if(y>z)
{
printf(“The Biggest number=%d”,y);
}
else
{
printf(“The Biggest number=%d”,z);
}
}
getch();
}
Output
Enter the three numbers: 528
The Biggest number = 8

 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;
}
}

Flow chart for Switch-Case statement


Example Program
/*Program to provide multiple functions such as 1.Addition 2.Subtraction
3. Multiplication 4.Division by using switch statements.*/
#include<stdio.h>
#include<conio.h>
void main()
{
float c;
inta,b,n;
printf(“\n MENU”);
printf(“\n 1.Addition”); printf(“\
n 2.Subtraction”); printf(“\
n3.Multiplication”); printf(“\n
4.Division”); printf(“\n 0.Exit”);
printf(“\nEnter yourchoice:”);
scanf(“%d”,&n);
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
switch(n)
{
case1:
c= a + b;
printf(“\nAddition:%d”,c);
break;
case2:
c= a -b;
printf(“\nSubtraction:%d”,c);
break;
case3:
c= a * b;
printf(“\nMultiplication:%d”,c);
break;
case4:
c= a / b;
printf(“\nDivision:%d”,c);
break;
case0:
exit();
break;
default:
printf(“Invalidchoice”);
break;
}
getch();
}
Output
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:
2Entertwonumbers:4020
Subtraction:20

1.5.1.2 Looping Statements


 A loop is defined as a block of statements which are repeatedly executed for
certain number of times.The`C’ language supports three types of loop
statements.
1. for statement
2. while statement
3. do-while statement
 For Loop Statement
 The for loop allows to execute a set of instructions until a certain condition is
satisfied. Condition may be predefined or open-ended.
 The syntax for loop this is follows:
for<initial value>;<condition>;<incrementation/decrementation>)
{
Block of statements;
}

Flowchart of the For loop statement


 Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or
not. Incremention / decrementation is to increment/decrement the loop counter
value each time the program segment has been executed.
Example Program1
/*Program to Generate numbers from 1to10*/
#include<stdio.h>vo
id main()
{
int i,n;
printf(“\nEnter the limit”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf(“%d\n”,i);
}
getch();
}
Output
Enter the limit:10
1
2
3
4
5
6
7
8
9
10
 While Loop Statement
 The syntax for the while loop statement is
while(condition)
{
Block of statements;
incr/decr;
}
 The while loop is often used when the number of times the loop is to be
executed is not known in advance. A sequence of statements is executed until
some condition is satisfied.
 When the condition specified inside the parenthesis the while loop is satisfied,
the control is transferred to the statements inside the loop and executes the body
of the loop. The loop continues until the condition is violated. The while tests
the condition before each iteration.
 If the condition initially fails the loop is skipped entirely even in the first
iteration itself. It is otherwise called as entry controlled loop.

Flowchart of the While loop

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.

Flow chart of the Do while loop


 The syntax for the do while loop is
do
{
statements;
}
while(condition);
/*Program to check the given number is palindrome o r not */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,t,s,r;
clrscr();
printf(“\nEnter the number”);
scanf(“%d”,&n);
t=n;
s=0;
do
{ r=n
%10;
s=(s*10)+r;
n=n/10;
}while(n>0);
if(t==s)
printf(“%dis a palindrome”,t); else
printf(“%dis not a palindrome”,t);
getch( ); }
Output
Enter the number 242
242 is a palindrome

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

1.8.2 Declaration of an Array


Array has to be declared before using it in C program.Declaring array means
specifying three things.
Data_type Data Type of Each Element of the array
Array_name Valid variable name
Size Dimensions of the
Array Arrays are declared using the following syntax:

Type name[size]

1.8.3 Initialization of arrays


Elements of the array can also be initialized at the time of declaration as in the
case of every other variable.When an array is initialized, we need to provide a value for
every element in the array. Arrays are initialized using the following syntax:
Type array_name[size] ={list of values};

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};

1.9 ONE DIMENSIONAL ARRAY


 It is also known as single-dimensional arrays or linear array or vectors
 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript
Example
Declaration of Single Dimensional Array
 An array must be declared before being used.Declaring an array means
specifying three things.
1. Datatype
2. Name
3. Size
Syntax

Data type array name [array size];

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]

Example: int a [2][3]; //aisanintegerarrayof2rowsand3columns


Number of elements=2*3=6
Initialization
1. By using an initialization list,2D array can be initialized.
e.g.int a[2][3]= {1,4,6,2}

a 1 4 6
2 0 0

2. The initializers in the list can be


e.g int a[2][3]={{1,4,6}, {2}};
Program1.35
/*Example for two dimensional array handling*/
#include<stdio.h>
void main( )
{
Int a[10][10],i,j,sum,d,n1,n,row sum,col sum,dia sum;
printf(“Enter order[row][col] of the matrix\n”);
scanf(“%d %d”,&n,&n1);
printf(“Enter%d elements\n”,n1*n);
for(i=0;i<n;i++) for(j=0;j<n1;j++)
scanf(“%d”,&a[i][j]);
/*Program module to sum all elements* /
sum=0;
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
sum+=a[i][j];
printf(“Sumofallelements%d\n”,sum);
/* Program to module to sum row wise*/
for(i=0;i<n;i++)
{
Row sum=0;
for(j=0;j<n1;j++)
{
Row sum+=a[i][j];
printf(“row no= %d sum= %d\n”,i,row sum);

}
}
/*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

You might also like