You are on page 1of 22

UNIT 2 IMPERATIVE LANGUAGES

Structured Programming Need and Design issues. Block Structures (Pascal), types arrays,
records, sets, pointers, procedures, parameter passing, scope rules (in C).
Structured Programming (Pascal)
A Pascal program basically consists of the following parts:
Program name
Uses command
Type declarations
Constant declarations
Variables declarations
Functions declarations
Procedures declarations
Main program block
Statements and Expressions within each block
Comments
Program name
Name of the program
Uses command
comma delimited names of libraries
Type declarations
There are two type of declaration
Constant declarations
Constants are the terms that can't be changed during the execution of a program
Variables declarations
Variables are the terms that can be changed during the execution of a program

Mr.S.Boopalan, Asst. Prof., CSE,

Page 1

Functions declarations
These subprograms return a single value.
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Syntax:

function name(argument(s): type1; argument(s): type2; ...): function_type;

Example:

function max(num1, num2: integer): integer;

Procedures declarations
These subprograms do not return a value directly.
A procedure declaration tells the compiler about a procedure name and how to call the
procedure. The actual body of the procedure can be defined separately.
Syntax:

procedure name(argument(s): type1, argument(s): type 2, ... );

Example:

procedure findMin(x, y, z: integer; var m: integer);

Main program block


A programming language that permits the creation of blocks, including blocks nested
within other blocks, is called a block-structured programming language.
Statements and Expressions within each block
Which perform different computations or actions depending on whether a programmerspecified boolean condition evaluates to true or false. Apart from the case of branch
predication, this is always achieved by selectively altering the control flow based on
some condition.

Mr.S.Boopalan, Asst. Prof., CSE,

Page 2

Comments
you can place comments in your code that are not executed as part of the program. A
comment starts with /* symbol and ends with */ and can be anywhere in your program.
Comments can span several lines within your C program.
Every pascal program generally have a heading statement, a declaration and an execution part
strictly in that order. Following format shows the basic syntax for a Pascal program:
program {name of the program}
uses {comma delimited names of libraries you use}
const {global constant declaration block}
var {global variable declaration block}
function {function declarations, if any}
{ local variables }
begin
...
end;
procedure { procedure declarations, if any}
{ local variables }
begin
...
end;
begin { main program block starts}
...
end. { the end of main program block }

Block Structure:
Class of languages
Pascal is the best representative
designed for programmer flexibility than absolute run-time performance (procedural
languages)
Possess activation records but employ scope rules and nested block structures for
structured data.
There is some run-time penalty
Mr.S.Boopalan, Asst. Prof., CSE,

Page 3

Each block
Has a characteristic structure:
a header giving specification of parameters and results
followed by constant definition, type definitions, local variable
declarations other nested subprogram definitions
statements for the executable part
Example Program
program HelloWorld;
uses crt;
(* Here the main program block starts *)
begin
writeln('Hello, World!');
readkey;
end.

Structured Programming (C)


Documentation section
Preprocessor section
Definition section
Global declaration section
main()
{
Declaration part;
Executable part;
}
sub program section
{
Body of the subprogram;
}
Mr.S.Boopalan, Asst. Prof., CSE,

Page 4

Documentation section:
It consists a set of comment lines used to specify the name of program, the author and
other details etc.,
Comments:
Comments are very helpful in identifying the program features and under-laying logic of
the program. The lines begins with '/*' and ending with '*/' are known as comment lines.
These are not executable, the compiler is ignored anything in between /* and */.
Preprocessor section:
It is used to link system library files, for defining the macros and for defining the
conditional inclusion.
Eg :

#include<stdio.h>, #define A 10, #if def, #endif... etc.

Global Declaration Section:


The variables that are used in more than one function throughout the program are called
global variables and declared outside of all the function i.e., before main().
Declaration part:
This part is used to declare all the variables that are used in the executable part of the
program and these are called local variables.
Executable part:
It contains atleast one valid 'C' statement. The execution of a program begins with
opening brace '{' and ends with closing brace '}'. The closing brace of the main function
is the logical end of the program.
Example Program
#include <stdio.h>
main()
{
int number;
printf("Enter an integer\n");
scanf("%d",&number);
printf("Integer entered by you is %d\n", number);

Mr.S.Boopalan, Asst. Prof., CSE,

Page 5

return 0;
}
Arrays
An array is a collection of similar data items, that are stored under a common name. A
value in an array is identified by index or subscript enclosed in square brackets with array
name.
The individual data items can be integers, floating point numbers, characters and so on,
but they must be the same type and same storage class.
Arrays can be classified into
One-Dimensional arrays
Two-Dimensional arrays
Multi-Dimensional arrays
Array Declaration:

Arrays are declared in the same manner as an ordinary variables except that each array
name must have the size of the array i.e., number of elements accommodated in that
array.
Syntax:
datatype arrayname [size/subscript];
Example :
int a[5];
Where,
'a' is the name of the array with 5 subscripts of integer data types and the computer reserves five
storage locations.
One Dimensional Array:
/* Program to specifies how a character array can be used */
#include<stdio.h>
#include<conio.h>
void main()
{
/* Local definitions */
char word[] = {'F','R','I','E','N','D','S'};
int i;
clrscr();
Mr.S.Boopalan, Asst. Prof., CSE,

Page 6

/* Statements */
for(i=0;i<7;i + + )
printf("%c",word[i]);
printf("\n");
getch();
}

/* main */

Two Dimensional Arrays:


Two dimensional arrays are used in situation where a table of values needs to be stored in
an array.
These can be defined in the same fashion as in one dimensional array, except a separate
pair of square brackets is required for each subscript.
Two pairs of square brackets required for two dimensional array and three pairs required
for three dimensional arrays and so on.
Two dimensional arrays are stored in a row-column matrix, where the left index indicates
the row and the right indicates the column.
Syntax:
datatype [row size][column size];
Example:
Int [3][3];
/*Program using two dimension array */
#include<stdio.h>
main()
{
/*Local definitions */
int stud[4][2]; /*stud is a array name with 4 rows and 2 columns */
int i;
/*Statements */
for(i=0;i<=3;i+ + )
Mr.S.Boopalan, Asst. Prof., CSE,

Page 7

{
printf("\n Enter the %d Student roll no and Mark:",i);
scanf("%d %d",& stud[i][0], & stud[i][1]);
}

/*for */

for(i=0;i<=3;i+ + )
printf("%d Students roll no %d mark %d", i,stud[i][0], stud[i][1]);
}

/*main */

OUTPUT:
Enter the 0 student roll no and mark: 3977 80
Enter the 1 student roll no and mark: 17776 95
Enter the 2 student roll no and mark: 6682 82
Enter the 3 student roll no and mark: 6683 85
0 student

roll no 3977

mark 80

1 student

roll no 17776

mark 95

2 student

roll no 6682

mark 82

3 student

roll no 6683

mark 85

Three Dimensional Arrays:


Similarly, like one and two dimensional arrays. 'C' language allows multidimensional
arrays. The dimension with three or more called multi dimensional arrays.
Syntax:
Datatype [size1][size2][size3];
Example:
Int[3][3][3];

Mr.S.Boopalan, Asst. Prof., CSE,

Page 8

/* Program on multi dimensional array */


#include<stdio.h>
#include<conio.h>
void main()
{
/* Local definitions */
int i,j,k;
int a[2][3][4];
int b[3][4];
int c[4];
int cnt=0;
/* Statements */
clrscr();
for(i=0;i<2;i++ )
for(j=0;j<3;j++ )
for(k=0;k<4;k++ )
{
a[i][j][k] = cnt;
cnt++ ;
}

/* for */

print_onedim(a);
print_twodim(a);
print_threedim(a);
}

/* main */

print_onedim(int a[])
Mr.S.Boopalan, Asst. Prof., CSE,

Page 9

{
int i;
for(i=0;i<4;i++ )
printf("%d ",a[i]);
}

/* print_onedim() */

print_twodim(int a[][4])
{
int j;

/* Local definitions */

/* Statements */
for(j=0;j<3;j++ )
print_onedim(a[j]);
printf("\n");
}

/* print_twodim() */

print_threedim(int a[][3][4])
{
int j;

/* Local definitions */

/* Statements */
printf("Each two dimension matrix\n");
for(j=0;j<2;j++ )
print_twodim(a[j]);
getch();
}

/* print_threedim() */

Output:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 11
Each two dimension matrix
Mr.S.Boopalan, Asst. Prof., CSE,

Page 10

0 1 2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20 21 22 23
Records:
One record holds the information for a single entity. A record occupies a single line in a
text file. The record is a sequence of characters that ends with a record delimiter. The
record delimiter is typically the newline character (\n).

Consider a text file named winter.txt containing information about items of clothing. Each
record describes a specific item and the quantity of that item.
5 Pairs of Boots
2 Coats
3 Hats
3 Pairs of Gloves
To determine the number of records in this file, we count the number of newline characters:
// Number of Records
// records.c
#include <stdio.h>
int main(void)
{
FILE *fp = NULL;
int c, nrecs;
fp = fopen("winter.txt", "r");
if (fp != NULL) {
nrecs = 0;
do {
c = fgetc(fp);
if (c != EOF) {
if ((char)c == '\n')
nrecs++;
}
} while (feof(fp) == 0);
printf("%d records on file\n",
nrecs);
Mr.S.Boopalan, Asst. Prof., CSE,

4 records on file
Page 11

fclose(fp);
}
return 0;
}

Sets:
Sets are collection of unique elements. In C, a single Set contains elements of the same
type, such as either integers or characters. A Set is represented by putting curly brackets
around its elements. Sets are used for storing complex data in an organized form. For
example, a Set of whole numbers can be represented as:
X= {1,2,3,4,5,6,7,8}
Where, X is a Set containing eight whole numbers.

Types of Sets
Depending on the number of elements, there are different types of Sets.
Types

Description

NULL Set

An empty Set depicted as .

Subset

A Set X is the Subset of Y when every atom of X is present in


Y, depicted as XY, such as {1,2,3}{1,2,3,4}.

Superset

A set X is the superset of Y when Y is the Subset of X,


depicted as XY, such as {1,2,3,4}{1,2,3}.

Universal
Set

A Set X is the Universal Set of Sets Y and Z when X is the


Superset of Y and Z, depicted by . For example, {1,2,3,4,5}
is the Universal Set of Sets {1,2,3} and {4,5}.

Operations on Sets
You can perform these operations on Sets:

Union
Intersection
Difference

Mr.S.Boopalan, Asst. Prof., CSE,

Page 12

The Union of two Sets, X and Y, is a Set that contains all the distinct elements present in X and
Y. For example:
X={1,2,3} Y={4,5,6} then XUY or X Union Y={1,2,3,4,5,6}
The Intersection of two Sets X and Y, is a Set that contains the elements which are present in
both X and Y. For example:
X={1,2,3} Y={2,3,4} then XY or X Intersection Y={2,3}
The Difference of two Sets X and Y is a Set that contains all the elements of X, which are not
present in Y. For example:
X={1,2,3} Y={2,3,4} then X-Y or X Difference Y={1} and Y-X={4}
Implementation of Sets In C
Using C, you can perform various operations, such as Union, Intersection, and
Difference, on Sets. These operations can also be implemented using data structures, such
as Linked List and arrays.
#include<stdio.h>
main()
{
int a[3]={1,2,3},b[3]={2,3,4},c[3],i,n=0,j,temp=0;
/******************Union***************/
printf("Union of Sets X and Y is->");
for(i=0;i<3;i++)
{
c[i]=a[i];
}
for(i=0;i<3;i++)
{
for(j=0,n=0;j<3;j++)
{
if(c[j]==b[i])
n=1;
}
if(n==0)
{
c[j]=b[i];
}
}
for(i=0;i<=3;i++)
printf("%d\t",c[i]);
b[0]=2;
b[1]=3;
Mr.S.Boopalan, Asst. Prof., CSE,

Page 13

b[2]=4;
/*********************Intersection********/
printf("Intersection of Sets X and Y is->");
for(i=0;i<3;i++)
{
for(j=0,n=0;j<3;j++)
{
if(a[j]==b[i])
n=1;
}
if(n==1)
{
c[i]=b[i];
temp++;
}
}
for(i=0;i<temp;i++)
printf("%d\t",c[i]);
/******************Difference***********/
temp=0;
printf("\nDifference X-Y is->");
for(i=0;i<3;i++)
{
for(j=0,n=0;j<3;j++)
{
if(a[i]==b[j])
n=1;
}
if(n==0)
{
c[i]=a[i];
temp++;
}
}
for(i=0;i<temp;i++)
printf("%d\t",c[i]);
getch();
return;
}

In the code, the union of Sets X and Y is 1 2 3 4 5, Intersection of Sets X and Y is 2 3,


and Difference between X and Y is 1.
Pointers:
Mr.S.Boopalan, Asst. Prof., CSE,

Page 14

"A pointer is a variable, it may contain the memory address of the another variable."
Pointer can have any name that is legal for other variable. It is declared in the same
manner like other variables. It is always denoted by '*' operator.
Pointer is a variable that contain the address of another variable. Like normal variable
declared in 'C' pointers can also be declared.
Syntax
data-type

*pointer-name;

Description
data-type

Specifies the type of data to which the pointer points.


Pointer-name Specifies the name of the pointer. (It must preceded
with an (*) asterisk.

Example
int
char
float

*a;
*b;
*c;

int

*a mean 'a' contains the address of variable,


which is integer variable.
*b mean 'b' contain the address of variable,
which is character variable.
*c means 'c' contain the address of variable,
which is float variable.

char
float

Example Program:
/* Program to find the sum of two numbers using pointers */
#include<stdio.h>
#include<conio.h>
main( )
{
Mr.S.Boopalan, Asst. Prof., CSE,

Page 15

/* Local definitions */
int a,b,c;
int *a,*b;

/* *a,*b is a pointer variables */

/* Statements */
printf("\n Enter two integer value");
scanf("%d%d", & a, &b);
*a=& a;

/* &a and &b is a address variables */

*b=& b;
c=*a+ *b;
printf ("\n Sum of two integer is=%d", c);
}

/* main */

OUTPUT:
Enter two integer value: 10 20
Sum of two integer is=30
Procedure:
There are basically three steps involved in converting your ideas into what is to be done
to make it a working program. There are three steps involved in converting your idea of
what is to be done to a working program
Creating a source code in the form of the text file acceptable to the compiler.
Invoking the compiler to process the source code and produce an object file.
Linking all the object files and libraries to produce an executable 16
Before proceed let us summarize the steps that takes us to run a program in the form of a
flow chart.

Mr.S.Boopalan, Asst. Prof., CSE,

Page 16

As we said earlier it is the tradition to write a C program file name ending with the
extension .C.

Example: Below we give a program that computes the square root of a number and prints
it on the screen. Since it is a C program we name it as "myfile.c" , that is with an extension
".c".

1 #include
2 #include
3 main()
{
4 float x,y;
5 scanf("%f\n",&x);
6 y=sqrt(x); 7 printf("%f\n",y);
}

Mr.S.Boopalan, Asst. Prof., CSE,

Page 17

Lines 1 and 2 are header files. These files contain the math library functions and the input
output command functions. We need the math function library to use functions like
"sqrt", "log", "power" etc. We need the stdio library to use functions like "scanf" and
"printf" which reads and prints the data from the screen. More on this a little later.

The program given above just has a main body. Line 3 is declares the starting on this
part. The lines inside the { } following this are the part of the main program.
Line 4 is the declaration of the variables. Again we will see more on the variable types
later in this course. In this particular example we declare variables "x,y" as floating
points.
Line 5 reads the value of the variable from the screen.
Line 6 computes the square root of the variable "x" and put the value into variable "y".
Line 7 prints out this value of y.

Example: Let us now look at a C program that uses the library and another function.
#include<stdio.h>
#include<conio.h>
main()
{
float x,y;
printf("%f\n",&x);
y=sqrt(x);
printf("%f\n",y);
printf(); printf();
{
printf("The program is Over");
}
Parameter Passing:
Mr.S.Boopalan, Asst. Prof., CSE,

Page 18

There are various types of parameter passing techniques available in programming


languages later displayed below.
These are based on how actually parameter is passed to called function (Function which
is called) from calling function (Function which calls the other function also called Caller
function).
float square ( float ) ;
main( )
{
float a, b ;
printf ( "\nEnter any number " ) ;
scanf ( "%f", &a ) ;
b = square ( a ) ;
printf ( "\nSquare of %f is %f", a, b ) ;
}
float square ( float x )
{
float y ;
y=x*x;
return ( y ) ;
}
In above program main() calls the square() so main() is caller function and square() is
called function.
Following are types of parameter passing techniques which are widely used in
programming language

Call by Value
Call by Reference
Call by Value Result also called Copy restore
Call by Name
Call by Text
Call by Need

Call by Value:
The process of passing the actual value of variables is known as "call by value". When a
function is called in program, the values to the arguments in the function are taken by the
calling program; the value taken can be used inside the function.
Alteration to the value is not accepted inside the function in calling program but change
is locally available in the function.
Program:

Mr.S.Boopalan, Asst. Prof., CSE,

Page 19

/* Program to swap the two given variable * /


#include<stdio.h>
main ( )
{
/* Local definitions * /
int a=10, b=20;
/* Statements * /
printf ("\n Before swap a=%d,b=%d",a,b);
void swap(a,b);

/* swap is a function with parameters * /

printf ("\n After the calling the swap function,


a=%d,b=%d", swap(a,b);
}

/* main * /

void swap(x,y)
/* Local definitions * /
int x,y;
{
/* Statements * /
x=x+ y;
y=x-y;
x=x-y;
printf ("In swap function x=%d,y=%d",x,y);
}

/* swap * /

Mr.S.Boopalan, Asst. Prof., CSE,

Page 20

OUTPUT:
Before swap a=10, b=20.
In swap function x=20, y=10.
After calling the swap function a=10, b=20.
Call by Reference:
The process of calling a function using pointers to pass the addresses of variables is
known as "call by reference".
A function can be declared with pointers as its arguments. Such functions are called by
calling program with the address of a variable as argument from it.
Program:
/* Program to explain about call by reference */
#include<stdio.h>
main ( )
{
/* Local definitions */
int a=10, b=20;
/* Statements */
printf ("\n Before calling the function a&b is %d,%d",a,b);
void change(&a,&b); /* change is a function call with parameters */
printf ("\n After calling the function a&b is %d%d", a,b);
}

/* main */

void change(x,y)
Mr.S.Boopalan, Asst. Prof., CSE,

Page 21

/* Local definitions */
int x,y;
{
/* Statements */
x=x + 5;
y=y + 10;
printf ("In the function changes a&b is %d,%d",*x,*y);
}

/* change */

Output:
Before calling the function a& b is 10,20.
In the function changes a& b is 15,30.
After calling the function a& b is 15, 30.
Scope rules in C:
All statements should be written in lower case letters.
Blank space can be used between words.
No blank space should be used while declaring a variable, keyword, constant and
function.
Uppercase letters are used for symbolic constants.
User can write one or more statements in one line separated by (;)
i.e d=a+b;
f=b+c;
or
d=a+b; f=b+c;
The opening and closing should be balanced.

Mr.S.Boopalan, Asst. Prof., CSE,

Page 22

You might also like