Professional Documents
Culture Documents
Unit I 2
Unit I 2
SYLLABUS
TOTAL: 45 PERIODS
TEXT BOOKS:
REFERENCES:
Unit 1 Page 1
CS6202 PROGRAMMING AND DATA STRUCTURES
UNIT I
CONDITIONAL STATEMENTS
Unit 1 Page 2
CS6202 PROGRAMMING AND DATA STRUCTURES
else
{
statement 3;
statement 4;
}
Unit 1 Page 3
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 4
CS6202 PROGRAMMING AND DATA STRUCTURES
}
False
else Condition 1
{
True Statements
statement 2; False
Condition 2
}
} True
else Statements
Statements
{
statement 1;
}
Example:Write a program to find the maximum of three numbers using Nested if else
statement.
#include < stdio.h> Output
#include <conio.h> Enter the value of a & b: 7 8 5
void main ( ) b = 8 is greater.
{
int a, b,c;
clrscr( );
printf (“\n Enter the value of a, b, c:”);
scanf (“%d %d %d”, &a, &b, &c);
if(a>b && a>c)
printf(“\n a= %d is greater”, a);
else if (b>c)
printf(“\n b= %d is greater”, b);
else
printf(“\n c= %d is greater”, c);
getch( );
}
Unit 1 Page 5
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 6
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 7
CS6202 PROGRAMMING AND DATA STRUCTURES
Output
MENU
=================
[1] ADDITION
[2] SUBSTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[0] EXIT
=================
Unit 1 Page 8
CS6202 PROGRAMMING AND DATA STRUCTURES
CONTROL STATEMENTS
Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed.
They make it possible to make decisions, to perform tasks repeatedly or to jump from
one section of code to another.
Loop:
A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
Three types of loop control statements
1. for
2. while
3. do-while
for loop
The for loop is used to execute set of instructions repeatedly until the condition is
false.
Syntax of for loop:
for(initialize counter; test condition; increment/decrement counter)
{
statement 1;
statement 2;
}
(i) Initialise counter:
It is used to initialize the counter variable
(ii) Test condition:
It is used to test the condition.
(iii) Increment / decrement counter:
Unit 1 Page 9
CS6202 PROGRAMMING AND DATA STRUCTURES
While loop:
It is repetitive control structure used to execute the statements within the body
until the condition becomes false.
Syntax:
while(test condition)
{ Test Condition? Stop
body of the loop;
}
Body of the loop
Unit 1 Page 10
CS6202 PROGRAMMING AND DATA STRUCTURES
The while loop is top driven loop. The condition is evaluated first and if it is true,
then the body of the loop is executed.
After executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again.
This process is repeated until the condition becomes false
Then the control is transferred out of the loop.
{
statement; Condition
}
while(condition);
Unit 1 Page 11
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 12
CS6202 PROGRAMMING AND DATA STRUCTURES
Jumping statements
1. break
2. continue
3. goto
4. return
Unit 1 Page 13
CS6202 PROGRAMMING AND DATA STRUCTURES
Example
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
clrscr();
printf(“\n Enter a number:”);
scanf(‘%d”, &x);
if(x%2 = = 0)
goto even;
else
goto odd.
even:
printf(“ \n %d is even number” , x);
odd:
printf(“\n %d is odd number”, x);
}
Output
Enter a number: 7
7 is odd number.
Difference between Break and Continue
Break Continue
Exits from current block or Loop takes next iteration.
loop.
Control passes to next Control passes to the beginning of the
statement. loop.
Terminates the program. Never terminates the program.
Unit 1 Page 14
CS6202 PROGRAMMING AND DATA STRUCTURES
FUNCTIONS
A function is a sub-program that contains one or more statements to perform a
specified task. The C language supports two types of functions
i) Library functions (Predefined Function)
ii) User defined functions
Use or need of functions
The length of the source program can be reduced by dividing it into smaller
function.
If we want to perform a task repetitively then it is not necessary to re-write the
particular block of the program again and again.
Using functions, large programs can be reduced to smaller ones.
It is easy to debug and find out the errors in it.
It also increases readability.
Difference between user defined function and predefined function
The predefined or library functions are not required to be written by the
programmer. Their task is limited. The user can only use the functions but cannot change
or modify them.
Example: sqrt(81) gives result 9
The user defined function has to be written by the programmer at the time of
programming.
User defined functions
The function defined by the user according to their requirement is called user
defined function. The user can modify the function according to their requirement.
Working of function:
Whenever a function is called, control passes to the called function and working of
the calling function is temporarily stopped, when the execution of the called function is
completed then a control return back to the calling function and executes the next
statement.
Elements of User defined function:
i. Function declaration(prototype)
ii. Function call
Unit 1 Page 15
CS6202 PROGRAMMING AND DATA STRUCTURES
Function call :
A function can be called by typing the function name in a source program with
parameters.
Syntax : Example
function_name(); add();
function_name(parameters); add(a,b);
return_value = function_name(parameters); c=add(a,b);
Function definition :
It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics to perform a particular task.
Parameters :
Parameters provide the data communication between the calling function and called
function. There are two types of parameters.
a) Actual Parameters
b) Formal Parameters
Unit 1 Page 16
CS6202 PROGRAMMING AND DATA STRUCTURES
main()
{
------
------
function_name(x,y,z); // Function call
------- Actual Arguments
-------
}
function_name(a,b,c) // Function definition
{ Formal arguments
-----
-----
return( ); // Return value
}
a) Actual argument: The arguments of calling function or function call are formal
arguments.These are transferred from the calling program(main program) to the
called program(function).
b) Formal arguments: The arguments of called function are formal arguments.
c) Function name: A function must follow the same rule as variable.
d) Argument/parameter list: The argument list contains variable names enclosed
within the parenthesis. The formal arguments receive values from the actual
argument.
Return statement
The return statement may or may not send back any values to the main
program.
Syntax: return; (or) return(exp)
Types of Functions
i. Functions with no arguments and no return values.
ii. Functions with arguments and no return values.
iii. Functions with arguments and return values.
iv. Functions with no arguments and return values.
Unit 1 Page 17
CS6202 PROGRAMMING AND DATA STRUCTURES
Syntax :
main( ) fun1( )
{ {
……… …………
fun1( ); …………
……… …………
} }
Unit 1 Page 18
CS6202 PROGRAMMING AND DATA STRUCTURES
Syntax :
main() fun1(x,y)
{ {
……… …………
fun1(a,b); …………
……… …………
} }
Eg:
void main( )
{
void add(int, int);
int a,b; Output :
printf(“Enter two numbers”); Enter two numbers 10 20
scanf(“%d%d”,&a,&b); Sum = 30
add(a,b);
}
void add(int x, int y)
{
int z;
z= x+y;
printf(“Sum = %d”,z);
}
Unit 1 Page 19
CS6202 PROGRAMMING AND DATA STRUCTURES
Syntax :
main() data_type fun1(x,y)
{ {
……… …………
c = fun1(a,b); …………
……… return(z);
}
}
Example:
void main()
{ Output :
int add(int, int); Enter two numbers 10
20
int a,b,c; Sum = 30
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“Sum = %d”,c);
}
int add(int x, int y)
{
int z;
z= x+y;
return(z);
}
Unit 1 Page 20
CS6202 PROGRAMMING AND DATA STRUCTURES
Syntax :
main() data_type fun1()
{ {
……… …………
c = fun1( ); …………
……… return(z);
} }
Example:
void main( ) Output :
{ Enter two numbers 10 20
int add( ); Sum = 30
c=add(a,b);
printf(“Sum = %d”,c);
}
int add( )
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
Unit 1 Page 21
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 22
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 23
CS6202 PROGRAMMING AND DATA STRUCTURES
{
int i;
for(i=1;i<=n;i++)
fact=fact*i;
return(fact);
}
Output
Enter an integer number: 5
The factorial of the given number is 120
Unit 1 Page 24
CS6202 PROGRAMMING AND DATA STRUCTURES
Call by reference
The address of arguments are copied into the parameter inside the function, the
address is used to access the actual arguments used in the cell. In this example
program, pointers are passed to function.
Here changes made in the arguments are permanent.
Unit 1 Page 25
CS6202 PROGRAMMING AND DATA STRUCTURES
ARRAYS
The ordinary variables are capable of storing one value at a time. Array variables are
able to store more than one value at a time.
Definition of array
An array is a collection of similar data types in which each element is located in
separate memory locations.
An array is a collection of similar dataitems that are stored under a common name.
Declaration of array
Declaration of an array is done as
int a[5];
Unit 1 Page 26
CS6202 PROGRAMMING AND DATA STRUCTURES
It tells the compiler that a is an integer type of array and can store 5 integers. The compiler
reserves 2 bytes of memory for each integer array element.
Array initialization
Array initialization is done as
int a[5]= { 1, 2, 3, 4, 5};
Here 5 elements are stored in an array a. The array elements are stored sequentially in
separate locations. Initialization of array elements begins from subscript 0. Array
elements are called by array names followed by the subscript value. E.g. a[0] refers to 1 st
element, a[1] refers to 2nd element and so on.
Characteristics of array
Any particular element of an array can be modified separately without disturbing
other elements.
int a[5] = { 1, 2, 3, 4, 5}; a[4] = 10;
Any element of an array a[ ] can be assigned to another ordinary variable or array
variable of its type. b = a[2]; a[3] = a[4];
Here the elements are stored in continuous memory locations. It is assumed that the
starting memory location is 2000. Each integer element requires 2 bytes. Therefore the
subsequent element appears after a gap of two locations.
Unit 1 Page 27
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 28
CS6202 PROGRAMMING AND DATA STRUCTURES
Output
Enter how many numbers to sort: 5
Enter Number 1: 8
Enter Number 2 : 3
Enter Number 3 : 2
Enter Number 4 : 1
Enter Number 5: 9
The numbers in ascending order
1 2 3 8 9
Unit 1 Page 29
CS6202 PROGRAMMING AND DATA STRUCTURES
printf(“key found”);
found=1;
break;
}
}
if(found=0)
printf(“Key not found”);
getch();
}
Unit 1 Page 30
CS6202 PROGRAMMING AND DATA STRUCTURES
printf(“\n”);
}
}
}
Output
Elements of an array
1 2 3
4 5 6
7 8 9
Unit 1 Page 31
CS6202 PROGRAMMING AND DATA STRUCTURES
if(small>a[i])
small=a[i];
}
printf("Smallest element: %d",small);
return 0;
}
Output:
Enter the size of the array: 4
Enter 4 elements in to the array: 2 7 8 1
Largest element: 8
Smallest element: 1
Unit 1 Page 32
CS6202 PROGRAMMING AND DATA STRUCTURES
strcpy(s[j],t);
}
}
}
Unit 1 Page 33
CS6202 PROGRAMMING AND DATA STRUCTURES
Output
Enter the order of matrix: 2 3
Enter the elements of matrix:
1 5 7 8 9 6
Original Matrix is
1 5 7
8 9 6
The Matrix Transpose is
1 8
5 9
7 6
4. Matrix Addition
Unit 1 Page 34
CS6202 PROGRAMMING AND DATA STRUCTURES
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf("\nEnter the number of rows and columns for matrix : \n");
scanf("%d%d",&r,&c);
printf("\nEnter values of matrix A :");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
printf("\nEnter values of matrix B :");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<=c;j++)
c[i][j]=a[i][j]+b[i][j];
}
Unit 1 Page 35
CS6202 PROGRAMMING AND DATA STRUCTURES
}
}
Output
Enter the number of rows and columns of matrix A : 2 2
Enter the number of rows and columns of matrix B : 2 2
Enter the values of matrix A: 1 2 3 4
Enter the values of matrix B : 7 4 6 5
The resultant matrix is
8 6
9 9
5. Matrix multiplication
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,r1,r2,c1,c2;
printf("\nEnter the row and column of first matrix");
scanf("%d %d",&r1,&c1);
printf("\nEnter the row and column of second matrix");
scanf("%d %d",&r2,&c2);
if(c1!=r2 )
{
printf("Matrix mutiplication is not possible");
printf("\nColumn of first matrix must be same as row of second matrix");
}
else
{
printf("\nEnter the First matrix->");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
Unit 1 Page 36
CS6202 PROGRAMMING AND DATA STRUCTURES
Output
Unit 1 Page 37
CS6202 PROGRAMMING AND DATA STRUCTURES
Preprocessor
Introduction
Preprocessor is a program that processes our source program before compilation.
These are placed before the main ( ) function in source program. The compiler examines
the preprocessor for any preprocessor directives. If there is any preprocessor directive, the
appropriate actions are taken and then the source program is moved for compilation. The
preprocessor operates under the following preprocessor directives.
i. File inclusion
ii. Macro Substitutions
iii. Conditional Inclusion
i. File Inclusion
This is used to include an external file, which contains functions or some other
macro definitions to our source program, so we need not rewrite that functions and
macros in our source program.
Syntax #include “file name” and #include<file name>
Unit 1 Page 38
CS6202 PROGRAMMING AND DATA STRUCTURES
Where file name is the name of the file that can be included in our source program.
When filename is quoted, it searches for that file in current directory and then in
standard directories. When the file is included in Angle brackets the included file is
searched only in standard directories.
ii. Macro Substitutions
This is used to define symbolic constants in the source program. The identifier or
string or integer defined is replaced by Macro substitution.
Syntax: #define identifier string / integer.
The preprocessor accomplish the task specified in #define statement. This
statement is also placed before the main ( ) function in source program. The
preprocessor replaces the every occurrence of an identifier by the specified string or
integer in source program.
There are three different forms of macros.
Example:
#define A 10
#define CITY “CHENNAI”
The #define A 10 macro substitutes ‘A’ with 10 in all occurrences in the source
program.
Unit 1 Page 39
CS6202 PROGRAMMING AND DATA STRUCTURES
Output
The value is 40
iii. Conditional Inclusion
These are used to control the preprocessor with conditional statements.
The preprocessor directives are
#if ,#else ,#elif, #endif these directives allow you to conditionally include portions of
code based on the outcome of the expression.
Eg: #define MAX 10
void main( )
{
#if MAX>100
printf(“ max above 100”);
#else
printf(“max below 100”);
endif
}
#if is associated with endif. In the above code the else part is compiled, #else directive
works much like the else. #elif means elseif, establishes an if-else-if chain for multiple
compilation option.
#ifdef, #ifndef , #undef:
#ifdef means if defined ,. #ifndef means if not defined
Syntax:
#ifdef macro-name
Statements;
endif
#ifndef macro-name
Statements;
endif
Eg:
#define TED 10
void main()
Unit 1 Page 40
CS6202 PROGRAMMING AND DATA STRUCTURES
{
#ifdef TED
printf(“hi TED”);
#else
printf(“hi anyone”);
#endif
#ifndef RALPH
printf(“RALPH not defined”);
#endif
}
The above program will print hi TED and RALPH not defined.
#undef – removes a previously defined definition of the macro name that follows it.
#undef macroname
#define LEN 100
-----
-----
#undef LEN //LEN undefined at this point
Rules for Defining Preprocessor
Every processor must start with # symbol.
The preprocessor is always placed before main ( ) function.
The preprocessor cannot have termination with semicolon.
There is no assignment operator in #define statement.
The conditional macro must be terminated (#ifdef, #endif).
POINTERS
Introduction to Pointer
A pointer is a memory variable. It contain the memory address of another variable.
It is declared in the same manner like other variables. It is always denoted by ‘*’
operator.
Unit 1 Page 41
CS6202 PROGRAMMING AND DATA STRUCTURES
A pointer is a variable; its value is also an address. Each variable has two
attributes: address and value. A variable can take any value specified by its data type.
A pointer to an integer is a variable that can store the address of that integer.
Features of Pointer
Pointers are used for saving memory space.
Using the pointer, execution time is decreased, because data is directly accessed from
memory.
Pointers reduce the length and complexity of the program.
The pointer assigns the memory space and also releases the memory. Dynamically
memory is allocated.
We can efficiently access the memory with pointers.
Advantages of using Pointer
Pointers are more compact and efficient code.
Pointers can be used to achieve clarity and simplicity.
Pointers are used to pass information between function and its reference point.
Pointers enable us to access the memory directly.
Pointers also provide an alternate way to access an array element.
Variation in pointer declarations
Pointer Declaration
Pointer is a variable, it contain the address of another variable. The pointer variable
can be declared as
Syntax: datatype *pointer_name;
Where datatype specifies the type of data to which the pointer point. Pointer name
specifies the name of the pointer. It must preceded with an (*) asterisk. The asterisk
operator is called indirection operator. Another name for the indirection operator is the
dereferencing operator.
Example:
int *x; - Here x is an integer pointer. It contains the address of integer variable.
float *y; - Here y is an float pointer. It contains the address of float variable.
Unit 1 Page 42
CS6202 PROGRAMMING AND DATA STRUCTURES
getch( );
}
Pointer to Pointer
The pointer is known as a variable containing address of another variable. The
pointer variable also has an address. The pointer variable containing address of another
pointer variable is known as pointer to pointer.
Unit 1 Page 44
CS6202 PROGRAMMING AND DATA STRUCTURES
void Pointers
Pointers can also be declared as void type. Void pointers cannot be dereferenced
without explicit type conversion. This is because; being void the compiler cannot determine
the size of the object that the pointer points to. Though void pointer declaration is possible,
void variable declaration is not allowed.
Write a program to declare a void pointer. Assign address of int, float and char
variables to the void pointer using type casting method. Display the contents of
various variables.
#include<stdio.h>
#include<conio.h>
int p;
float d;
char c;
void *pt ;
void main( )
{
pt = &p;
*(int*)pt = 12;
printf(“\n p = %d”, p);
pt = &d;
*(float*)pt=5.4;
printf(“\n d = %f”,d);
pt = &c;
*(char*)pt=’s’;
printf(“\n c = %c”,c);
}
Function Pointers
Unit 1 Page 45
CS6202 PROGRAMMING AND DATA STRUCTURES
}
// calling from main
int main( )
{
void (*subPtr)(int, int) = subtract;
(*subPtr)(10, 2);
}
Here the subtract function takes two parameters, both integers, subtracts one from
the other and prints the result. We create our subPtr function pointer with void (*subPtr)
(int, int). The only difference from before is now instead of empty parentheses on the end
when creating the function we have (int, int) which matches the signature of our new
function.
A Function Pointer with Parameters and Return Value
Let’s change our subtract function to be called subtract and to return the result
instead of printing
int subtract(int x, int y); // function prototype
int subtract(int x, int y)
{
return x - y;
}
int main( )
{
int (*subtractPtr)(int, int) = subtract;
int y = (*subtractPtr)(10, 2);
printf("Subtract gives: %d\n", y);
}
Here the subtract function returns an int. The prototype and function signatures
have changed as would be expected. We create our subtractPtr function pointer with int
(*subtractPtr)(int, int). The only difference from before is instead of void we have an int
return value. This matches our subtract method signature.
Passing a Function Pointer as a Parameter
Let’s move on to a little more complex example where we pass a function pointer
into another function as a parameter.
int add(int x, int y); // function prototypes
int subtract(int x, int y);
Unit 1 Page 47
CS6202 PROGRAMMING AND DATA STRUCTURES
Unit 1 Page 48