You are on page 1of 40

Department of Computer Technology

Program Logic Design in C


3rd Semester C.T.

LIST OF EXPERIMENTS

1. Demonstrate the use of Iterative & Non-Iterative Control Statements

(if...else, for, while, do...while, switch statement).

2. To demonstrate the use of function.


3. To demonstrate the use of One Dimensional Array (Sorting).
4. To demonstrate the use of Searching
5. To demonstrate the use of Two Dimensional Array.
6. To demonstrate the use of Array of Structures.
7. To demonstrate the use of File Handling Functions.
8. To demonstrate the application of File Handling.
9. To demonstrate the use of Command Line Argument
10. To demonstrate the use of pointers & function arguments.
11. To study the concept of Dynamic Memory Allocation in C.
12. To demonstrate the use of Graphics concepts (Line Generation Algorithms).
13. To demonstrate the application of Graphics concepts.
14. To study the basic concept of Object Oriented Methodology.
15. To study the concept of class definition in Object Oriented Methodology.

Kavikulguru Institute of Technology & Science


Page |1
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 01
Date:
Aim: To demonstrate the use of Iterative & Non-Iterative Control Statements
(if...else, for, while, do...while, switch statement).

Problem Definition:
1. Write a program to determine whether the entered number is even or odd.
2. Write a program to find the factorial value of any number entered through the
keyboard.
3. Write a program to read the character from the keyboard and find whether
the character is vowel or consonants using do – while loop.
4. Write a program which takes two integer operands and one operator from the
user, performs the operation and then prints the result.
Theory:
Control statements:
Statements controls the flows of execution are known as Control Statement. They are
also known as decision making statements.
1. Non-iterative Statements: The following are the non-iterative statements
a) Simple if statement.
b) If - else statement.
c) Nested if - else statement.
d) else - if ladder statement.
e) Ternary operator.
f) Switch statement.
2. Iterative Statements / Loop control statement: The iterative statements allow
set of instruction to be performed until certain condition is reached. C
provides three different types of loops.
a) For loop.
b) While loop.
c) Do - While loop.
a) Simple if statement:
The general form of a simple if - statement is
if (test expression){ Statement - block;
} Statement - X;
b) The if….else statement :
The if …else statement is an extension of the simple if statement. The general
form is
if (test expression){
True - block statements
}
else{
False - block statements

Kavikulguru Institute of Technology & Science


Page |2
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

}
statement - x
Loop control statement:
In looping, sequences of statements are executed until some conditions for
termination of the loop are satisfied. A program loop therefore consists of two
segments, one known as body of loop and other known as control statement. The
control statement tests certain conditions & then directs the repeated execution of the
statement contained in the body of the loop.A lopping process would include the
following four steps:
1. Setting & initialization of the condition variable.
2. Execution of the statement in the loop.
3. Test for a specified values of the condition variable for execution of the loop.
4. Incrementing & updating the condition variable.
The test may either to determine whether the loop has been repeated the specified
number of times or to determine whether a particular condition has been met.

For loop:
The for loop is an entry-controlled loop that provides a more concise loop
control structure. The general form of for loop is
for ( initialization ; test–condition ; increment )
{
body of the loop;
}
The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements
such as i = 1 & count = 0. The variable i & count are known as loop - control
variables.
2. The value of the control variable is tested using the test - condition. The test -
condition is a relational expression, such as i < 10 that determine when the
loop will exit. If the condition is true, the body of the loop is executed;
otherwise the loop is terminated & the execution continues with the statement
that immediately follows the loop.
3. When the body of loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. The control variable
is incremented using an assignment statement such as i = i + 1 & the new
value of the control variable is again tested to see whether it satisfied, the
body of the loop is again executed. This process continues till the value of
control variables fails to satisfy the test - condition.

Problem Definations:

Kavikulguru Institute of Technology & Science


Page |3
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

1. Write a c program to calculate the following sum :


Sum = 1 – x 2 / 2 ! + x 4 / 4 ! – x 6 / 6 ! +x 8 / 8 ! – x 10 / 10 !
2. Write a program to print out all Armstrong numbers between 1 and 500. If
sum of cubes of each digit of the number is equal to the number itself, then
the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) +
(5*5*5)+(3*3*3)
3. According to the Gregorian calendar, it was Monday on the date 01/01/1900.
If any year is input through the keyboard write a program to find out what is
the day on 1st January of this year.
4. Given the length and breadth of a rectangle, write a program to find whether
the area of the rectangle is greater than its perimeter. For example, the area of
the rectangle with length = 5 and breadth = 4 is greater than its perimeter.
5. Write a program to generate all prime numbers between 1 to n, where n is a
value supplied by the user.

Conclusion: Students are advised to write conclusion on separate sheet.


Review Questions

1. What is looping? What is the use of looping?

2. Explain how nested for loops are executed?

3. What is the difference between while loop & do while loop?

4. What are the three points to be considered while working with any types of loop?

5. What is the difference between for loop and while loop?

EXPERIMENT NO: 02
Date:
Aim: To demonstrate the use of function.

Kavikulguru Institute of Technology & Science


Page |4
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Problem Definition:
1. Write a function power (a, b) to calculate the value of a raised to b.
2. Write a general purpose function to demonstrate the concept of call by value
and call by reference to swap the contents of two variables.
Theory:
Function:
Function act as the fundamental building blocks of large program. Each function
normally performs a specific task. Every C program must contain at least one
function named as main where the program always begins execution. The main
function may call other function with in it. C functions can be classified into two
categories namely library function & user defined function.
Library functions are not written by user. Functions like printf(), scanf(), sqrt() and
strcat() etc. are examples of library function.
User defined functions has to be developed by the user, at the time of writing a
program. User defined function have three part, they are:
1. Function definition.
2. Function call.
3. Function declaration.

1. Function definition :
A function definition, also know as function implementation shall include the
following elements.
 Function name.  Local variable declaration.
 Function type.  Function statements.
 List of parameters.  A return statement.

All six elements are grouped into two parts, namely

 Function header (First three elements)


 Function body (second three elements)

Function definition is an independent program module that is specially written to


implement the requirements of the function. In order to use this function definition
we need to invoke it at a required place in the program. This is known as the
“function call”. The statement that calls the function definition is referred to as the
“function calling statement”. The calling program should declare any function (like
declaration of variable) that is to be used later in the program. This is known as the
function declaration or function prototype.

The general format of function definition is


function_type function_name (list of parameters) /* function header */
{
local variable declaration;

Kavikulguru Institute of Technology & Science


Page |5
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

executable statement 1;
executable statement 2;
……..
……..
return statement;
}
function_type specifies the type of values (like float or double) that the function is
expected to return to the program calling the function.
function_name specifies the name of the user defined function. A function has to be
given an appropriate name, which should specify the purpose of the function.
List of Parameters are the input given to a function by specifying the caller (calling
program) can ask the function to process a set values. Whatever parameter the
calling function passes is called actual parameter. & whatever parameter the function
has received are called the formal parameter. The actual parameter values are copied
to the formal parameter.
Function body contains the declaration & statements necessary for performing the
required task. The body enclosed in braces, contain three parts, in the order given
below:
1. Local declaration that specifies the variable needed by the function.
2. Function statements that performed the task of the function.
3. A return statement that return the value evaluated by the function.
If a function does not return any value, user can omit the return statement.
Its return type should be specified as void.
2. Function calls :
A function can be called by using the function name followed by a list of actual
parameters or arguments enclosed in parentheses. The actual parameter values are
copied to the formal parameter.
3. Function declaration :
Like variables, all function in a C program must be declared, before they are
invoked. A function declaration (also known as function prototype) consists of four
parts.
 Function type (return type).
 Function name.
 Parameter list.
 Terminating semicolon.
The general format of function declaration is
Function_type function_name (parameter list);
Example: int mul ( int m , int n ) ; /* Function prototype */
Exercise:
1. Write a function to calculate the factorial value of any integer entered through
the keyboard.
2. A positive integer is entered through the keyboard. Write a function to obtain
the prime factors of this number.

Kavikulguru Institute of Technology & Science


Page |6
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

For example: prime factor of 24 are 2, 2, 2 and 3, whereas prime factor of 35


are 5 and 7.

Review Question:
1. What is function? State the advantages of using functions?
2. Explain the difference between the following :
a. Actual and Formal arguments. b. Global and Local variables.
3. What is the purpose of return statement in function definition?
4. What is difference between function definition and declaration?

Kavikulguru Institute of Technology & Science


Page |7
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO: 03
Date :
Aim : To demonstrate the use of One Dimensional Array (Sorting).

Problem Definition :
1. Write a program that implement the following sorting methods to sort a given list of
integers in ascending order :
a. Selection sort.
b. Bubble Sort
c. Insertion Sort

Theory :
To make searching process faster and efficient, the sorting mechanism is applied.
Sorting is the Process of arranging the data either in ascending or descending
order, for numerical data items and alphabetic order for character data items.
There are different sorting techniques used to sort the data either in ascending or
descending order. They are as follows.
1. Selection Sort.
2. Bubble Sort.
3. Insertion Sort.

1. Selection Sort :
In Selection sort Technique is based on the extension of minimum and maximum
technique. The minimum value of the array if located and then it is placed on the
first position of the array and the first element at the found location. Then in the
remaining elements, once again the next smallest element is found and is placed
in the second position of the array and so on. This process continues. In the end,
the next to last element is compared with the last element. Now the entire
elements are sorted into ascending order.
The selection sort makes first pass in n-1 comparisons, the second pass in n-2
comparison and so on. Hence the total numbers of comparisons are:
(n-1) + (n-2) + ……..1 = n*(n-1)/2

Algorithm :
Steps required to perform the selection sort are as follows.
1. Declare an array an array of 10 integers.
2. Take the loop and read an array element from the keyboard, in unsorted
manner this array is before sorting .
3. Take the for loop and print the unsorted array elements.
4. Perform the selection sort.
Take the for loop and do the following procedure:
The element a[i] is compared with a[j]. If a[i] is greater than a[j] then
interchange the values using temporary variable i.e. temp variable.

Kavikulguru Institute of Technology & Science


Page |8
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

if(a[i]>a[j]) Then interchange the element


temp=a[i]
a[i]=a[j]
a[j]=temp
5. Use for loop and print these sorted array element. This array obtained after
sorting.

2. Bubble Sort :
In Bubble sort, each element is compared with its adjacent element. If the first
element is larger than the second one then the position of the element are
interchanged, otherwise not. Then the next element is compared with its adjacent
element and the same process is repeated for the entire array element. At the end
of the first pass, the largest element of the list bubbles out and take the desired
i.e. the last location in the list.
During the Second or next iteration the same process is repeated leaving the
largest element at the appropriate location. During this pass, the second largest
element occupies the second last position. The same process is repeated until no
more elements are left for the comparison. Finally the array is sorted one.

Algorithm:
Steps required to perform the Bubble sort are given below.
1. Declare an array an array of 10 integers.
2. Take the loop and read an array element from the keyboard, in unsorted
manner this array is before sorting.
3. Take the for loop and Print the unsorted array elements.
4. Perform the Bubble sort, Take the for loop and do the following procedure:
The element a[j] is compared with a[j + 1]. If a[j] is greater than a[j + 1] then
interchange the variable using temporary i.e. temp variable.
if(a[j]>a[j + 1]) Then interchange the element is given in following step
temp = a [j]
a[j] = a[j + 1]
a[j + 1] = temp
5. Use for loop and print the sorted array element this array elements. This array
obtained after sorting.

3. Insertion Sort :
An insertion sort, Sorts a set of values by inserting values into an existing sorted
array. Suppose an array a with n elements a[1], a[2], …… a[n] is in the memory.
This algorithm scans a from a[1] to a[n], inserting each element a[k] into its
proper position.

Algorithm :
Steps required to perform the Insertion sort are given below.
1. Declare an array an array of 10 integers.

Kavikulguru Institute of Technology & Science


Page |9
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

2. Take the loop and read an array element from the keyboard, in unsorted
manner this array is before sorting.
3. Take the for loop and Print the unsorted array elements.
4. Perform the Insertion Sort, Take the for loop and do the following procedure:
a. The element a[1] is trivially sorted.
b. The element a[2] is instead before or after a[1] such that a[1], a[2] are sorted.
c.The element a [3] is inserted into its proper place in a[1],a[2]. a[2] can be.
 Before a[1]
 After a[2]
 Between a[1] and a[2].
Such that a[1], a[2], a[3] is sorted and so on.
5. Use for loop and print the sorted array element. This array obtained after
sorting.

Exercise :
1. Write a program to read a set of strings and sort names in the list.
2. Write a program to find out the number of letters, words in a given string
using arrays.
3. Write a program to concatenate the given two strings into third string using
arrays.
4. Write a program to convert string into opposite case letter using pointers.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Questions:
1. What do you mean by sorting?
2. What are the different sorting Technique?
3. What is the advantage of sorting?
4. What do you mean by arranging element in ascending order?
5. What do you mean by arranging element in descending order?
6. Where the sorting technique is useful?

Kavikulguru Institute of Technology & Science


P a g e | 10
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 04
Date :
Aim : To demonstrate the use of Searching.

Problem Definition :
1. Write a program to perform the following searching operations for the key
value in a given list of integers :
a. Linear Search.
b. Binary Search.

Theory :
Searching it is process, it is use to search the array element whether the element is
present in the array or not. If the element is present in the array then the search is
successful otherwise Search is unsuccessful.

1. Linear Search :
Linear Searching is also called as Sequential Searching. In Linear Search, each
element of an array is accessed one by one sequentially and see whether it is
desired or not. A Search will be unsuccessful if all the elements are accessed and
the desired element is not found.
Linear Search can be defined as the technique, which traverses the array
Sequentially to locate the given item. In the average case, half of the sizes of the
array have to be scanned i.e.n/2 elements. The time taken or the number of
comparisons made in searching an item in a search space determines the
efficiency of the technique. If the desired item or element is found on the first
position then only one comparison is made. If a desired item is found on the last
position then n comparisons have to be made. If a desired item is found some
where in the middle on an average, the number of comparison will be (n+1)/2.
The worst case efficiency of this technique is O(n).
Algorithm :
Steps are required for the Linear Search.
1. Declare a one dimensional array e.g. take an array of 10 integer number.
2. Read and Print the array element.
3. Scan or Read an element to be searched, Store in a variable ele.
4. If the search element is match with any element of an array then it will
display the message.
“ Element found at position I and search is successful.
else
“ Element is not found and search is unsuccessful.”

2. Binary Search:-

Kavikulguru Institute of Technology & Science


P a g e | 11
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Binary Search is an extremely efficient algorithm. This search technique searches


the given item in minimum possible comparisons. The basic requirement for this
search technique is the array should be sorted. The Steps are carried out in this
search technique is as follows:
Step 1 : First find out the middle element of the array.
Step 2 : Compare the middle element with an item.
Step 3 : There are three Cases:
a. If it is a desired element then search is successful.
b. If it is less than desired item then search only the first of the array.
c. If it is greater than the desired element search in the second half of the array.
This process is repeated until an element is found or the search areas get
exhausted. In this algorithm each item we are reducing the search area. So the
number of comparisons is decreasing. In the worst case, the number of
comparison can be almost long (N+1). It is an efficient algorithm as compared to
linear search but the array has to be sorted before applying binary search
algorithm on array elements.

Exercise :
1. Write a program to delete n characters from a given position in a given string.
2. Write a program to determine whether the given string is a palindrome or
not.
3. Write a program to count the lines, words and characters in a given text.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question :
1. What do you mean by Searching?
2. What are the different searching techniques used?
3. What is the initial value assign to low and high variables of Binary Search?
4. What are the advantages of Linear Search?
5. What is the advantage of Binary Search ?
6. Is sorted array required for Binary Search? Justify your answer.
7. How the mid value is calculated in Binary Search ?
8. What do you mean by sub array?
9. If there are large amount of values stored in an array which searching
technique is useful ? And why?
10. If array consist of 3 elements which searching technique is useful?

EXPERIMENT NO : 05
Date :

Kavikulguru Institute of Technology & Science


P a g e | 12
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Aim : To demonstrate the use of Two Dimensional Array.

Problem Definition:
1. Write a ‘C’ program to perform Transpose of matrix without using
another array.
2. Write a program to pick up the largest number from any 5 row by 5
column matrix.

Theory :
It is possible to have more than one-dimensional arrays. There will be a situation
where a table of values will have to be stored. These can be done in two-
dimensional arrays. Two-dimensional arrays are also know as matrix and
sometimes tables. Two dimensional array are declared as:
typename array_name [row_size] [column_size];
The typename specifies the type of array, array_name should be any valid
identifier name of C, the row_size is a number which specifies number of rows of
a matrix and column_size is a number which specifies number of columns of a
matrix. As in single dimensional arrays each dimensional of the array is indexed
from zero to its maximum size minus one. The first index selects the row and the
second index selects the column.
The initialization of two-dimensional array is same as that of single dimensional
array. Two-dimensional arrays may be initialized by following their declaration
with a list of initial values enclosed in braces.
Example: int arr[2][3] = { 0, 0, 0, 1, 1, 1};
Initializes the element of the first row to zero and the second row to one. The
initialization is done row by row. The array element arrangements in the row and
column form are conceptually true. This is because memory doesn’t contain row
and columns. In memory whether it is one-dimensional or two-dimensional
array, the array element are stored in a contiguous memory location.
The arrangement of array elements of two dimensional array in memory as
shown below:
num[0][0] num[0][1] num[1][0] num[1][1]

16 21 26 09

Kavikulguru Institute of Technology & Science


P a g e | 13
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Algorithm :
1. Initialize the two-dimensional array element.
2. Scan the values of two dimensional array elements.
3. Print the two-dimensional array element i.e. original matrix element.
4. Initialize the loop and implement the logic
if ( j > i )
{
temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
5. Print the resultant matrix of two-dimensional array.
6. Finish.

Exercise :
1. Write a program to perform addition of two matrices.
2. Write a program to determine matrix is symmetric or not (a matrix is said to
be symmetrical when A = ‘A’)

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:
1. Explain the concept of Two-dimensional array.
2. What are the different method to initialize the two dimensional array?
3. What is mean by static allocation method?
4. What is mean by dynamic allocation method?
5. What is the difference between static allocation and dynamic allocation
method?
6. How does C handle the values in an array internally?
7. What is an array variable? How does it differ from an ordinary variable?
8. What are the conditions that must be specified by all the elements of any
given array?

Kavikulguru Institute of Technology & Science


P a g e | 14
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO: 06
Date :
Aim : To demonstrate the use of Array of Structures.

Problem Definition :
1. Create a structure to specify data on students given below: Roll number, Name,
Department, Course, Year of joining. Assume that there are not more than 450
students in the college.
a. Write a function to print the name of all students who joined in a particular
year.
b.Write a function to print the data of a student whose roll number is given.

Theory :
Structures:
A structure is a package of one or usually more variables which are grouped under a
single name. Structures are not like arrays: a structure can hold any mixture of
different types of data: it can even hold arrays of different types. A structure can be
as simple or as complex as the programmer desires.
The word struct is a reserved word in C and it represents a new data type, called an
aggregate type. It is not any single type: the purpose of structures is to offer a tool
for making whatever shape or form of variable package that a programmer wishes.
Any particular structure type is given a name, called a structure-name and the
variables (called members) within a structure type are also given names.

Declarations
A structure is declared by making a blank template for a variable package.
struct PersonalData
{
char name[namesize];
char address[addresssize];
int YearOfBirth;
int MonthOfBirth;
int DayOfBirth;
};

Alternatively, typedef can be used to cut down a bit on typing in the long term. This
type definition is made once at the head of the program and then subsequent
declarations are made by using the new name:
typedef struct
{
char name[namesize];
char address[addresssize];
int YearOfBirth;

Kavikulguru Institute of Technology & Science


P a g e | 15
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

int MonthOfBirth;
int DayOfBirth;
}
PersonalData;
then declare:
PersonalData x;

Arrays of Structures
Just as arrays of any basic type of variable are allowed, so are arrays of a given type
of structure. Although a structure contains many different types, the compiler never
gets to know this information because it is hidden away inside a sealed structure
capsule, so it can believe that all the elements in the array have the same type, even
though that type is itself made up of lots of different types. An array would be
declared in the usual way:
int i;
struct PersonalData x,array[size];

The members of the arrays would then be accessed by statements like the following
examples:
array[i] = x;
array[i] = array[j];
array[i].YearOfBirth = 1987;
i = array[2].MonthOfBirth;

Exercise :
1. Write a program that compares two given dates. To store a date use a
structure that contains three members namely date, month and year. If the
dates are equal then display message as “Equal” otherwise “Unequal”.
2. Crete a structure to specify data of customers in a bank. The data to be stored
is: Account Number, Name, Balance in account. Assume maximum of 200
customers in the bank.
a. Write a function to print the Account number and name of each
customer with balance below Rs. 100.
b. If a customer requests for withdrawal or deposit, it is given in the form:
Acct. no, amount, code(1 for deposit, 0 for withdrawal)
Write a program to give message, “The balance is insufficient for the
specified withdrawal”.

Kavikulguru Institute of Technology & Science


P a g e | 16
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 07
Date :
Aim : To demonstrate the use of File Handling Functions.

Problem Definition :
1. Write a program to read file and display its contents along with line numbers before
each line.
2. Write a program to append the contents of one file at the end of another.

Theory :
Files and Devices :
Files are places for reading data from or writing data to. This includes disk files and
it includes devices such as the printer or the monitor of a computer. C treats all
information which enters or leaves a program as though it were a stream of bytes: a
file. The most commonly used file streams are stdin (the keyboard) and stdout(the
screen), but more sophisticated programs need to be able to read or write to files
which are found on a disk or to the printer etc.
An operating system allows a program to see files in the outside world by providing
a number of channels or portals (inlets and outlets) to work through. In order to
examine the contents of a file or to write information to a file, a program has
to open one of these portals. The reason for this slightly indirect method of working
is that channels/portals hide operating system dependent details of filing from the
programmer. Think of it as a protocol. A program which writes information does no
more than pass that information to one of these portals and the operating system's
filing subsystem does the rest. A program which reads data simply reads values
from its file portal and does not have to worry about how they got there. This is
extremely simple to work in practice. To use a file then, a program has to go through
the following routine:
 Open a file for reading or writing. (Reserve a portal and locate the file on disk
or whatever.)
 Read or write to the file using file handling functions provided by the
standard library.
 Close the file to free the operating system portal for use by another program
or file.
A program opens a file by calling a standard library function and is returned a file
pointer, by the operating system, which allows a program to address that particular
file and to distinguish it from all others.

Files Generally
C provides two levels of file handling; these can be called high level and low level.
High level files are all treated as text files. In fact, the data which go into the files are
exactly what would be seen on the screen, character by character, except that they

Kavikulguru Institute of Technology & Science


P a g e | 17
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

are stored in a file instead. This is true whether a file is meant to store characters,
integers, floating point types. Any file, which is written to by high level file handling
functions, ends up as a text file which could be edited by a text editor.
High level text files are also read back as character files, in the same way that input is
acquired from the keyboard. This all means that high level file functions are identical
in concept to keyboard/screen input/output.
The alternative to these high level functions, is obviously low level functions. These
are more efficient, in principle, at filing data as they can store data in large lumps, in
raw memory format, without converting to text files first. Low level input/output
functions have the disadvantage that they are less programmer friendly than the
high level ones, but they are likely to work faster.

File Positions
When data are read from a file, the operating system keeps track of the current
position of a program within that file so that it only needs to make a standard library
call to read the next part of the file and the operating system obliges by reading some
more and advancing its position within the file, until it reaches the end. Each single
character which is read causes the position in a file to be advanced by one.
Although the operating system does a great deal of hand holding regarding file
positions, a program can control the way in which that position changes with
functions such as ungetc() if need be. In most cases it is not necessary and it should
be avoided, since complex movements within a file can cause complex movements
of a disk drive mechanism which in turn can lead to wear on disks and the
occurrence of errors.

High Level File Handling Functions


Most of the high level input/output functions which deal with files are easily
recognizable in that they start with the letter `f'. Some of these functions will appear
strikingly familiar. For instance:
fprintf() fscanf()
fgets() fputs()
These are all generalized file handling versions of the standard input/output library.
They work with generalized files, as opposed to the specific files stdin and stdout
which printf() and scanf() use. The file versions differ only in that they need an extra
piece of information: the file pointer to a particular portal. This is passed as an extra
parameter to the functions. They process data in an identical way to their standard
I/O counterparts. Other filing functions will not look so familiar. For example:
fopen() fclose() getc() ungetc();
putc() fgetc() fputc() feof()

Opening files:
A file is opened by a call to the library function fopen(): this is available
automatically when the library file <stdio.h> is included. There are two stages to
opening a file: firstly a file portal must be found so that a program can access
information from a file at all. Secondly the file must be physically located on a disk

Kavikulguru Institute of Technology & Science


P a g e | 18
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

or as a device or whatever. The fopen() function performs both of these services and,
if, in fact, the file it attempts to open does not exist, that file is created anew. The
syntax of the fopen() function is:
FILE *returnpointer;
returnpointer = fopen("filename","mode");
or
FILE returnpointer;
char *fname, *mode;
returnpointer = fopen(fname,mode);

The filename is a string which provides the name of the file to be opened. Filenames
are system dependent so the details of this must be sought from the local operating
system manual. The operation mode is also a string, chosen from one of the
following:
r : Open file for reading w : Open file for writing
a : Open file for appending rw :Open file for reading and writing
(some systems)

This mode string specifies the way in which the file will be used.
Finally, returnpointer is a pointer to a FILE structure which is the whole object of
calling this function. If the file (which was named) opened successfully
when fopen() was called, returnpointer is a pointer to the file portal. If the file could
not be opened, this pointer is set to the value NULL. This should be tested for,
because it would not make sense to attempt to write to a file which could not be
opened or created, for whatever reason.
A read only file is opened, for example, with some program code such as:
FILE *fp;
if ((fp = fopen ("filename","r")) == NULL)
{ printf ("File could not be opened\n");
error_handler();
}
Closing a file:
A file is closed by calling the function fclose(). fclose() has the syntax:
int returncode;
FILE *fp;
returncode = fclose (fp);
fp is a pointer to the file which is to be closed and returncode is an integer value
which is 0 if the file was closed successfully. fclose() prompts the file manager to
finish off its dealings with the named file and to close the portal which the operating
system reserved for it. When closing a file, a program needs to do something like the
following: if (fclose(fp) != 0)
{ printf ("File did not exist.\n");
error_handler();
}

Kavikulguru Institute of Technology & Science


P a g e | 19
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Exercise:
1. Write a program to find the size of a text file without traversing it character
by character.
2. Suppose a file contains student’s records with each record containing name
and age of a student. Write a program to read these records and display them.
3. What is purpose of the library function fflush() ?
4. Explain about binary files.
5. Write in details about fread() and fwrite() function.

Kavikulguru Institute of Technology & Science


P a g e | 20
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 08
Date :
Aim : To demonstrate the application of File Handling.

Problem Definition :
1. Write a program to display the contents of text file on the screen. Make
following provisions:
Display the contents inside a box draw with opposite corner co-ordinates
being (0,1) and (79, 23). Display the name of the file whose contents are being
displayed and the page numbers in the zeroth row. The moment one
screenful of file has been displayed, flash a message ‘press any key..’ in 24 th
row. When a key is hit, the next page’s contents should be displayed, and so
on till the end of file.

Theory :

Opening files:
A file is opened by a call to the library function fopen(), this is available
automatically when the library file <stdio.h> is included. There are two stages to
opening a file: firstly a file portal must be found so that a program can access
information from a file at all. Secondly the file must be physically located on a disk
or as a device or whatever. The fopen() function performs both of these services and,
if, in fact, the file it attempts to open does not exist, that file is created anew. The
syntax of the fopen() function is:
FILE *returnpointer;
returnpointer = fopen("filename","mode");
or
FILE returnpointer;
char *fname, *mode;
returnpointer = fopen(fname,mode);

The filename is a string which provides the name of the file to be opened. Filenames
are system dependent so the details of this must be sought from the local operating
system manual. The operation mode is also a string, chosen from one of the
following:
r Open file for reading
w Open file for writing
a Open file for appending
rw Open file for reading and writing (some systems)
This mode string specifies the way in which the file will be used.
Finally, returnpointer is a pointer to a FILE structure which is the whole object of

Kavikulguru Institute of Technology & Science


P a g e | 21
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

calling this function. If the file (which was named) opened successfully
when fopen() was called, returnpointer is a pointer to the file portal. If the file could
not be opened, this pointer is set to the value NULL. This should be tested for,
because it would not make sense to attempt to write to a file which could not be
opened or created, for whatever reason.
A read only file is opened, for example, with some program code such as:
FILE *fp;
if ((fp = fopen ("filename","r")) == NULL)
{
printf ("File could not be opened\n");
error_handler();
}

Closing a file:
A file is closed by calling the function fclose(). fclose() has the syntax:
int returncode;
FILE *fp;
returncode = fclose (fp);
fp is a pointer to the file which is to be closed and returncode is an integer value
which is 0 if the file was closed successfully. fclose() prompts the file manager to
finish off its dealings with the named file and to close the portal which the operating
system reserved for it. When closing a file, a program needs to do something like the
following:
if (fclose(fp) != 0)
{
printf ("File did not exist.\n");
error_handler();
}

fprintf():
This is the highest level function which writes to files. Its name is meant to signify
"file-print-formatted" and it is almost identical to its stdout counterpart printf(). The
form of the fprintf() statement is as follows:
fprintf (fp,"string",variables);

where fp is a file pointer, string is a control string which is to be formatted and the
variables are those which are to be substituted into the blank fields of the format
string. For example, assume that there is an open file, pointed to by fp:
int i = 12;
float x = 2.356;
char ch = 's';
fprintf (fp, "%d %f %c", i, x, ch);

Kavikulguru Institute of Technology & Science


P a g e | 22
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

The conversion specifiers are identical to those for printf(). In fact fprintf() is related
to printf() in a very simple way: the following two statements are identical.
printf ("Hello world %d", 1);
fprintf (stdout,"Hello world %d", 1);

fscanf():
The analogue of scanf() is fscanf() and, as with fprintf(), this function differs from its
standard I/O counterpart only in one extra parameter: a file pointer. The form of
an fscanf() statement is:
FILE *fp;
int n;
n = fscanf (fp,"string",pointers);

where n is the number of items matched in the control string and fp is a pointer to
the file which is to be read from. For example, assuming that fp is a pointer to an
open file:
int i = 10;
float x = -2.356;
char ch = 'x';
fscanf (fp, "%d %f %c", &i, &x, &ch);

The remarks which were made about scanf() also apply to this function: fscanf() is a
dangerous function in that it can easily get out of step with the input data unless the
input is properly formatted.

Exercise :

1. Write a program to copy one file to another. While doing so replace all lowercase
characters to their equivalent uppercase characters.
2. Write a program that merges lines alternately from two files and writes the results
to new file. If one file has less number of lines than the other, the remaining lines
from the larger file should be simply copied into the target file.

Kavikulguru Institute of Technology & Science


P a g e | 23
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 09
Date :
Aim : To demonstrate the use of Command Line Argument.

Problem Definition :
1. Write a program for command line arguments, to display number of
arguments and their names.
1. Write a program for copying content of one file to another by using command
line arguments.

Theory :
Command Line Argument :
Every C program, after compilation creates an executable file with the extension
‘.exe ’ for example, if a file is created with the name ‘first.c’, after compilation
‘first.exe’ is created, which can be run or executed from the command prompt
without C editor.
When information is passed to the function, they are pass by using the method
knows as argument passing. Argument can be pass to any function either standard
or user defined functions. main () is also a function, in many situation we may need
to pass the argument to the function. but, in C programming language every
program starts with a main () function and that it marks the way is command line
argument. When the arguments are pass to the main () function from the command
prompt are called as command line arguments.
When arguments are pass to main (), they are received in two arguments named
‘argc’ and ‘agrv’. The information contained in the command line is passed on to the
program through these arguments when the main () is called up by the system.
1. argc : An argument argc is a counter, counts the total nmber of arguments
passed from command prompt to the main ().
2. argv : An argument argv is an array of pointers to string, that points to each
command line arguments.
For example,
C:\> TC > fcopy source.c destination.c
Here, ‘fcopy’ is thr executable file, obtained after compiling ‘fcopy.c’.
‘source.c’ source file name and ‘destination.c’ is the destination file name.
There arguments are passed from the command line to the main (), hence,
the content of argc will be three and argv which is array of pointers to string
will contain the address of each of there arguments pass from the command
prompt. In our example, three arguments are passed ‘fcopy’, ‘source.c’, and
‘destination.c’. The argv, will contain:
 argv[0] - contain address of string ‘fcopy’.
 argv[1] - contain address of string ‘source.c’.
 argv[2] - contain address of string ‘destination.c’.
The following program demonstrates the use of command line arguments.

Kavikulguru Institute of Technology & Science


P a g e | 24
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

In order to access the command line arguments, we must declare the main
function and its parameters are follows:

main ( int argc, char * argv[ ] )


{
…….
…….
…….
}

The first parameter in the command line is always the program name and therefore
argv[0] always represent the program name.

Exercise:
1. Write a program that will receive a filename and a line of text as a command
line argument and write the text to the file.
2. Write a program using command line arguments to search for word in a file
and replace it with the specified word. The usage of program is as shown
below :
C :> change <old word> <new word> <file name>

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:
6. What is standard library? Why is c standard library needed?
7. What are the functions of these header files :
ctype.h math.h string.h stdlip.h ?
3. Distinguish between the following functions :
d. islower() and tolower().
e. isupper() and to upper().
4. What are the text mode graphics functions? Which header file is require?
5. What are the various parameters required for initialization of graphics
mode?

Kavikulguru Institute of Technology & Science


P a g e | 25
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO : 10
Date :
Aim : To demonstrate the use of pointers & function arguments.

Problem Definition :
1. Write a function which receives a float and an int from main(), finds the product of
these two and returns the product which is printed through main().
2. Write a function that receives five integers and return the sum and average of these
numbers. Call this function from main() and print the result in main().

Theory :
Parameter passing :
The technique used to pass data from one function to another is known as parameter
passing. Parameter or arguments passing can be done in two ways:
1. Call by value. i.e. passing value of the parameter or arguments.
2. Call by reference. i.e. passing addresses of the parameter or
arguments.

1. Call by value :
Also known as pass by value, value of actual parameter in the calling function are
copied to the variable in the parameter list (formal parameter) of the called function.
The called function works on the copy & not on the original values of the actual
parameters. This ensures that the original data in the calling function cannot be
changed accidentally.
Example :

void main () int swap ( int a , int b)


{ {
/* variable declaration */ /* variable declaration */
…………… ……………
…………… ……………
swap ( x , y ); t = a;
…………… a = b;
…………… b = t;
} ……………
……………
}
The actual arguments in the calling function are copied into corresponding formal
arguments. i.e. x value will be copied into a variable, y value will be copied into b

variable. Within swap function a & b values are swapped but it will not affect the x
& y which are in main function. Hence x & y values remain same.

Kavikulguru Institute of Technology & Science


P a g e | 26
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

2. Call by reference :
Also known as pass by pointers & pass by address, the memory address of the variable
(actual parameter) rather than the values in the calling function are sent (copied into
formal parameter) to the called function.
The called function directly works on the data in the calling function & the changed
values are available in the calling function for its use.
Example :

void main () int swap ( int * a , int * b)


{ {
/* variable declaration */ /* variable declaration */
…………… ……………
…………… ……………
swap ( & x , & y ); t = * a;
…………… * a = * b;
…………… * b = t;
} ……………
……………
}
The actual arguments addresses in the calling function are copied into
corresponding formal arguments. i.e. x address will be copied into a variable, y
address will be copied into b variable. Within swap function a & b values are
swapped & it will manipulates values present on the address specified by the actual
argument which are in the main function. Hence (x & y) values in main function & (a
& b) values in swap function are swapped.

Exercise :
1. Write a function that receives marks by a student in three subjects and returns
the average and percentage of these marks. Call this function from main() and
print the result in main().
2. Write a program to swap two numbers using call by reference method and
display the number before, during and after the function calling.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:
1. What is call by reference technique ? What is the difference between the call
by reference and call by value technique used with functions ?
2. Differentiate between pointer (*) and address (&) operator using examples ?
3. What do you mean by pointer arithmetic? Discuss the use of pointer with
arithmetic operators (+ and -) and unary operators (++ and --).
4. What are the storage classes? Give the classification of storage classes.
5. What will be the output of the following programs :

Kavikulguru Institute of Technology & Science


P a g e | 27
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

a. main () d. main ()
{ {
int k = 35, *y, *z; int i = -5, j = -2;
z = &k; junk (i, &j);
/* suppose address of k is 1008 printf(“i = %d j = %d”, i, j);
*/ }
y = z; junk (i, j)
*z ++ = *y ++; int i, *j ;
k ++; {
printf(“k = %d z = %d i=i*i;
y = %d”, k, z, y); *j = *j * *j ;
} }
e. main ()
b. main () {
{ float a = 7.999999;
int a = 100, *b, **c, ***d; float *b, *c;
b = &a ; b = &a;
c = &b ; c = b;
d = &c ; printf(“%d %d %d\n”, &a, b, c);
printf(“ %d %d %d %d”, a, printf(“%d %d %d %d\n” a, *(&a),
*b, **c, ***d); *b, *c );
} }

c. main () f. main ()
{ {
int i = 5, j = 2; int i = 3, j = 4, k, l;
junk ( &i, &j ); k = addmult (i, j);
printf(“\n %d %d”, i , j); l = addmult (i , j);
} printf(“\n %d %d”, k, l);
}
junk (int *i, int *j) int addmult (int ii, int jj)
{ {
*i = *i * *i ; int kk, ll;
*j = *j * *j ; kk = ii + jj;
} ll = ii * jj;
return (kk, ll);
}

EXPERIMENT NO: 11
Date:
Aim: To study the concept of Dynamic Memory Allocation in C.

Kavikulguru Institute of Technology & Science


P a g e | 28
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Problem Statement:
Write a program to demonstrate the use of dynamic memory allocation function,
such as allocation and reallocation of memory.

Theory:
Use Dynamic Memory Allocation in C

C dynamic memory allocation refers to performing manual memory management


for dynamic memory allocation in the C programming language via a group of
functions in the C standard library, namely malloc, realloc, calloc and free.

The following functions are used in c for purpose of memory management.


1. malloc()
2. calloc()
3. realloc()
4. free()

The malloc function

Pointer = (type *) malloc (size in bytes);


example:
int * p;
p = (int *) malloc (sizeof (int));
* p = 5;

First we declare a pointer, which is still pointing nowhere. Then the pointer, not the
content but the pointer itself is equal to a pointer type int that contains the memory
address space for an int. Sizeof () gets the space it occupies what you want, if you
put int in, such as 2 bytes, because we have assigned two bytes. This feature also
serves to get the size of pointers, variables, or whatever it takes.

calloc() function
The calloc function is used to allocate storage to a variable while the program is
running. This library function is invoked by writing calloc (num,size).This function
takes two arguments that specify the number of elements to be reserved, and the size
of each element in bytes and it allocates memory block equivalent to num * size . The
function returns a pointer to the beginning of the allocated storage area in memory.
The important difference between malloc and calloc function is that calloc initializes

Kavikulguru Institute of Technology & Science


P a g e | 29
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

all bytes in the allocation block to zero and the allocated memory may/may not be
contiguous.
calloc function is used to reserve space for dynamic arrays. has the following form.

void * calloc (size_t n, size_t size);

Number of elements in the first argument specifies the size in bytes of one element to
the second argument. A successful partitioning, that address is returned, NULL is
returned on failure.

For example, an int array of 10 elements can be allocated as follows.


int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.


int * array = (int *) malloc (sizeof (int) * 10);

realloc() function

With the function realloc, you can change the size of the allocated area once. Has the
following form.

void * realloc (void * ptr, size_t size);

The first argument specifies the address of an area that is currently allocated to the
size in bytes of the modified second argument. Change the size, the return value is
returned in re-allocated address space. Otherwise it returns NULL.

Size may be smaller but larger than the original. If you have small, reduced what
was written in part will be inaccessible. If you increase the portion of the region
will remain an indefinite increase.

The address of the source address changed, but the same could possibly be different,
even if the different areas of the old style, because it is automatically released in the
function realloc, for the older areas it is not necessary to call the free
function. However, if the function fails and returns NULL, realloc, the older area is
to remain still valid. Therefore, the first pointer argument of the function realloc,
both can be NULL pointer return value is not returned.

Kavikulguru Institute of Technology & Science


P a g e | 30
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

free() function

Next, how to release the reserved area, which will use the function free. Has also
been declared in stdlib.h, which has the following form.

void free (void * ptr);

The argument specifies the address of a dynamically allocated area. You can then
free up the space. Specify an address outside the area should not be dynamically
allocated. Also, if you specify a NULL (or NULL if the same holds for a given
pointer variable), the free function is guaranteed to do nothing at all. In addition, if
you try to re-release has already been freed space, so do not know what would be,
and should never be.

In addition, the space freed by the function free, guarantee that there is no data
remains intact. Thus, if once released, should not be accessing the same area.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:

1. Why does malloc(0) return valid memory address ? What's the use?
2. Difference between calloc() and malloc()?
3. What is static memory allocation and dynamic memory allocation?
4. What is the difference between new/delete and malloc/free?

Kavikulguru Institute of Technology & Science


P a g e | 31
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO: 12
Date:
Aim : To demonstrate the use of Graphics concepts (Line Generation Algorithms).

Problem Definition:
1. Write a program to draw a straight line by using simple algorithm.
2. Write a program to draw a straight line by using DDA (Digital
Differential Analyzer).

Theory:
Line Generation Algorithms:
To draw a line requires a raster refresh display is a matrix of discrete cell. Each cell
requires an intensity level. Since it is a point plotting display hence it is not
possible to draw a straight line from one addressable point to other point except in
case of horizontal, vertical and diagonal lines. Thus display is required by which
an approximation can be generated on the screen, but not the real line by setting
those pixel position which are in the vicinity of the line. For this purpose an
algorithm is needed to select those raster location or pixel position which when
selected and set to require intensity, gives an approximation of line and the
approximation generated depends upon how the algorithm makes selection of
raster location or pixel position.
The simplest algorithm is the line drawing algorithm. This algorithm makes the
use of differential equation of line to obtain recursion relation defining the co-
ordinate of next point in term of co-ordinate of current point. This recursive
relation is then used to select pixel position.
If x and y are incremented in x and y direction then for straight line, equation
will be,
y/x = (y2-y1) / (x2-x1)
Where x1, y1, x2, y2 are the co-ordinates of end points.

1. Algorithm :
f. Set the screen of computer in graphics mode.
b. Accept the starting points of line as x1, y1.
c. Accept the end point as x2, y2.
d. Calculate the slope pf line m=(y2-y1)/(x2-x1).
e. Increment the value of I from x1 to x2 each by one.
f. Calculate y=m * x1.
g. Plot (i, y)
h. Finish.

2. Algorithm:
b. The two endpoints of line are (x1, y1) and (x2, y2) assume that they are not
equal.

Kavikulguru Institute of Technology & Science


P a g e | 32
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

c. Approximate the line length as


If abs (x2-x1) >= abs (y2-y1)
length  abs (x2-x1)
else
length  abs (y2-y1)
d. Select the largest of del x or del y to be one raster unit.
Del x  (x2-x1) / length
Del y  (y2-y1) / length
e. x  x1 + 0.5 * sign (Del x)
y  y1 + 0.5 * sign (Del y)
sign() function returns the values –1, 0, +1 for –ve, Zero and +ve arguments.
f. If I = 1 then
Plot (integer (x), integer (y))
x  x + x
y  y + y
I=I +1
g. Go to step e. else perform next step
h. Stop.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:
1. What is known as slope of line?
2. What is fundamental unit of CRT display device?
3. What will be the faster method to draw the line?
4. Which command is used to initialize the graphics mode?
5. What is concept of DDA algorithm?

Kavikulguru Institute of Technology & Science


P a g e | 33
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO: 13
Date :
Aim : To demonstrate the application of Graphics concepts.

Problem Definition :
2. Write a menu Driven program to display following Geometrical figures.
1. Square 4. Triangle
2. Rectangle 5. Putpixel
3. Circle 6. Exit.
It should only terminate when option 5 is selected.

Algorithm :
I. Square ()
1. Set the screen of computer in graphics mode.
2. Accept the value of left, right, top & bottom.
3. The values of left, right, top & bottom should be same for Square.
4. Rectangle draws a rectangle in the current line style, thickness, and drawing
color.
5. Declaration of rectangle: void rectangle (int left, int top, int right, int
bottom);
6. (left, top) is the upper left corner of the rectangle, and (right, bottom) is its
lower right corner.
7. Finish.

II. Rectangle ()
1. Set the screen of computer in graphics mode.
2. Accept the value of left, right, top & bottom.
3. Rectangle draws a rectangle in the current line style, thickness, and drawing
color.
4. Declaration of rectangle: void rectangle (int left, int top, int right, int
bottom);
5. (left, top) is the upper left corner of the rectangle, and (right, bottom) is its
lower right corner.
6. Finish.

III. Circle ()
1. Set the screen of computer in graphics mode.
2. Accept center of circle i.e. value of x and y co-ordinate & the radius.
3. Circle draws a circle in the current drawing color.
4. Declaration of Circle (): void circle (int x, int y, int radius);
5. Finish.
IV. Triangle ()

Kavikulguru Institute of Technology & Science


P a g e | 34
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

1. Set the screen of computer in graphics mode.


2. Initialize the array variable.
3. drawpoly () draws the outline of a polygon.
4. Declaration of drawpoly() : void drawpoly (int num, int *polypoints);
5. drawpoly() draws a polygon with num points using the current line style and
color polypoints points to a sequence of (num * 2) integers.
6. Each pair of integers gives the x and y co-ordinates of a points on the
polygon. Draw a closed figure with n vertices, you must pass n+1 coordinates
to drawpoly().
7. fillpoly() draws and fills a polygon.
8. Declaration of fillpoly (): void fillpoly (int num, int *polypoints);
9. fillpoly() draws the outline of a polygon with num points in the current line
style and color and then fills the polygon using the current fill pattern and fill
color.
10. Finish.

V. Putpixel()
1. Set the screen of computer in graphics mode.
2. Accept the value of x and y coordinates.
3. Putpixel() plot a pixel at a specified point in a specified color.
4. Declaration of putpixel(): void putpixel(int x, int y, int color);
5. Finish.

Exercise :
1. Write a program to draw an arc on the output screen whose parameters are
user defined.
2. Write a program to draw an ellipse on the output screen whose parameters
are defined.

Conclusion: Students are advised to write conclusion on separate sheet.

Review Question :
1. What is the purpose of initgraph()?
2. Define putpixel()?
3. What is the necessity of closegraph() in program?
4. What are the functions used in the program?
5. Explain floodfill()?

Kavikulguru Institute of Technology & Science


P a g e | 35
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

EXPERIMENT NO: 14

Date:
Aim: To study the basic concept of Object Oriented Methodology.
Problem Definition:
Write a program that computes the roots of quadratic equation of the form ax 2+bx+c
=0 where a, b and c are the coefficients of the said equation.

Theory:
During the 60s, while computers were still in an early stage of development, many
new programming languages appeared. Among them, ALGOL 60, was developed as
an alternative to FORTRAN but taking from it some concepts of structured
programming which would later inspire most procedural languages, such as CPL
and its successors (like C++). ALGOL 68 also directly influenced the development of
data types in C. Nevertheless ALGOL was an non-specific language and its
abstraction made it impractical to solve most commercial tasks.
In 1963 the CPL (Combined Programming language) appeared with the idea of
being more specific for concrete programming tasks of that time than ALGOL or
FORTRAN. Nevertheless this same specificity made it a big language and, therefore,
difficult to learn and implement.
In 1967, Martin Richards developed the BCPL (Basic Combined Programming
Language) that signified a simplification of CPL but kept most important features
the language offered. Although it too was an abstract and somewhat large language.

In 1970, Ken Thompson, immersed in the development of UNIX at Bell Labs, created
the B language. It was a port of BCPL for a specific machine and system (DEC PDP-7
and UNIX), and was adapted to his particular taste and necessities. The final result
was an even greater simplification of CPL, although dependent on the system. It had
great limitations, like it did not compile to executable code but threaded-code, which
generates slower code in execution, and therefore was inadequate for the
development of an operating system. Therefore, from 1971, Dennis Ritchie, from the
Bell Labs team, began the development of a B compiler which, among other things,
was able to generate executable code directly. This "New B", finally called C,
introduced in addition, some other new concepts to the language like data types
(char).

In 1973, Dennis Ritchie, had developed the basis of C. The inclusion of types, its
handling, as well as the improvement of arrays and pointers, along with the later
demonstrated capacity of portability without becoming a high-level language,
contributed to the expansion of the C language. It was established with the book
"The C Programming Language" by Brian Kernighan and Dennis Ritchie, known as
the White Book, and that served as de facto standard until the publication of formal
ANSI standard in 1989.

Kavikulguru Institute of Technology & Science


P a g e | 36
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

In 1980, Bjarne Stroustrup, from Bell labs, began the development of the C++
language that would receive formally this name at the end of 1983, when its first
manual was going to be published. In October 1985, the first commercial release of
the language appeared as well as the first edition of the book "The C++
Programming Languages” by Bjarne Stroustrup.
During the 80s, the C++ language was being refined until it became a language with
its own personality. All that with very few losses of compatibility with the code with
C, and without resigning to its most important characteristics. In fact, the ANSI
standard for the C language published in 1989 took good part of the contributions of
C++ to structured programming.
From 1990 on, ANSI committee X3J16 began the development of a specific standard
for C++. In the period elapsed until the publication of the standard in 1998, C++
lived a great expansion in its use and today is the preferred language to develop
professional applications on all platforms.
C++ has been evolving, and a new version of the standard, c++09, is being
developed to be published before the end of 2009, with several new features.
Feature of object oriented programming
 Emphasis on data rather than procedure.
 Programs are divided into what are known as objects.
 Data structures are designed such that they characterized the objects.
 Function that operate on the data of an object are tied together in the data
structure.
 Data is hidden and cannot be accessed by external function.
 Objects may communicate with each other through function.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.
Characteristic of Object Oriented Programming
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

Conclusion: Students are advised to write conclusion on separate sheet.

Kavikulguru Institute of Technology & Science


P a g e | 37
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Review Questions:

1. What is the difference between C and C++?


2. Give the characteristic of OOP.
3. Define Class & objects.
4. Define Encapsulation?
5. Define Operator Overloading?
6. Define Function Overloading?
7. What is Polymorphism?

EXPERIMENT NO: 15
Date:
Aim: To study the concept of class definition in Object Oriented Methodology.

Kavikulguru Institute of Technology & Science


P a g e | 38
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

Problem Statement:
1. Write a program that defines a class Employee with appropriate data
members and member functions. The program should allow the data values
to be read as input and display the same as output.
2. Write a program to input an integer value from keyboard and display on
screen “WELDONE” that many times.
3. Write a c++ program that will ask for a temperature in Fahrenheit and display
it in Celsius.

Theory:
In the class data and function which are operating on the data are enclosed. A class
is defined as the collection of the data and the related function binded together. The
syntax of the class is given below.
Class <name of the class>
{
Declaration of the data members;
public/private:
declaration of the member function;
};
Example:-
#include<iostream.h>
class Area
{
int radius,area;
public:
void Getdata();
void Showdata();
};
void Area::Getdata()
{
cout<<”Enter the value of radius”;
cin>>radius;
}
void Area::Showdata()
{
cout<<”Area of circle =”<<area;
}

Kavikulguru Institute of Technology & Science


P a g e | 39
Ramtek - 441106
Department of Computer Technology
Program Logic Design in C
3rd Semester C.T.

void main()
{
clrscr();
Area obj1;
obj1.getdata();
obj1.showdata();
getch();
}

Algorithm:
1. Start
2. Create a class with the variables and the member function
3. Declare all functions as public.
4. Define the function.
5. Define the main function.
6. Define the objects of the class
7. Access the member function.
8. Stop.
Conclusion: Students are advised to write conclusion on separate sheet.

Review Question:
1. What is the use of public and private Keywords?
2. What is the use of data hiding?
3. Give the characteristic of Procedure Oriented Language.
4. What are different types of Polymorphism?
5. What do you mean by Inheritance ?

Kavikulguru Institute of Technology & Science


P a g e | 40
Ramtek - 441106

You might also like