Problem Solving Using C (Unit 5)
Problem Solving Using C (Unit 5)
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
memory can't be increased while executing memory can be increased while executing
program. program.
Now let's have a quick look at the methods used for dynamic memory allocation.
ptr=(cast-type*)malloc(byte-size)
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int n,i,*ptr,sum=0;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
for(i=0;i<n;++i)
{
printf("memory=%u data=%d\n",ptr,*ptr);
ptr++;
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
calloc() function in C:
ptr=(cast-type*)calloc(number, byte-size)
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
ptr=(cast-type*)realloc(ptr, new-size);
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
*ptr = 10;
*(ptr + 1) = 20;
getch();
}
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.
free(ptr);
Graphics:
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
initgraph(&gdriver, &gmode,"C:\\TURBOC3\\BGI");
getch();
closegraph();
Output:
Explanation of Code:
The first step in any graphics program is to include graphics.h header file. The graphics.h header
file provides access to a simple graphics library that makes it possible to draw lines, rectangles,
ovals, arcs, polygons, images, and strings on a graphical window.
The second step is to initialize the graphics drivers on the computer using initgraph method of
graphics.h library.
It initializes the graphics system by loading the passed graphics driver then changing the system
into graphics mode. It also resets or initializes all graphics settings like color, palette, current
position etc, to their default values. Below is the description of input parameters of initgraph
function.
graphicsDriver : It is a pointer to an integer specifying the graphics driver to be used. It tells the
compiler that what graphics driver to use or to automatically detect the drive. In all our
programs we will use DETECT macro of graphics.h library that instruct compiler for auto
detection of graphics driver.
driverDirectoryPath : It specifies the directory path where graphics driver files (BGI files) are
located. If directory path is not provided, then it will search for driver files in current working
directory. In all our sample graphics programs, you have to change path of BGI directory
accordingly where you Turbo C++ compiler is installed.
Borland Graphics Interface (BGI) is a graphics library that is bundled with several Borland
compilers for the DOS operating systems since 1987. The library loads graphic drivers (*.BGI)
and vector fonts (*.CHR) from disk so to provide device independent graphics support to the
programmers.
We have declared variables so that we can keep track of starting and ending point.
line(x1,y1,x2,y2);
Syntax : line(x1,y1,x2,y2);
Parameter Explanation
At the end of our graphics program, we have to unloads the graphics drivers and sets the screen
back to text mode by calling closegraph function.
closegraph deallocates the memory allocated by the graphics system and then restores the
screen to the mode it was in before calling initgraph.
Library functions used in drawing and filling images: There are some following functions:
arc(): This function draws an arc from start to the end point. It uses the radius and the angle
inputted in the function parametsr. Function prototye is
void arc (int x, int y, int start, int end, int radius)
bar(): The bar() functions draws a rectangular bar on the screen. It takes four parameters of
type int which are infact the points on the graphics screen, and fills the bar with the defined fill-
pattern.
Here left & top are the starting point for the rectangular bar from x and y coordinates
respectively and right & bottom are the ending point.
bar3d(): As the name suggests that this function will draw the 3 Dimensional rectangular bar on
the screen. Bar3d function takes six parameters of which four are the points , fifth one is the
depth of the bar and sixth is the flag to indicate the 3D view. Here is the prototype of the bar3d
function.
void bar3d(int left, int top, int right, int bottom, int depth, int topflag)
circle (): Draws the circle on the screen using a point(x,y) and the radius for the circle.
Here numpoints is the number of end points in the polygon. And points is the integer array
which contains the x and y coordinates of the points.
void ellipse(int x, int y, int start, int end, int xradius, int yradius)
floodfill(): This function fills an object drawn on the graphics screen with the defined color and
fill pattern. Now if the x,y coordinates lie within the boundaries of the object then it will fill the
interior of the object otherwise outside the object.
rectangle(): Draws a rectangular box on the screen using the points given in the parameters.
Write a Program to draw basic graphics construction like line, circle, arc, ellipse and rectangle.
#include<graphics.h>
#include<conio.h>
void main()
Int gd=DETECT,gm;
initgraph (&gd,&gm,"C:\\TURBOC3\\BGI");
setbkcolor(GREEN);
printf("\t\t\t\n\nLINE");
line(50,40,190,40);
printf("\t\t\n\n\n\nRECTANGLE");
rectangle(125,115,215,165);
printf("\t\t\t\n\n\n\n\n\n\nARC");
arc(120,200,180,0,30);
printf("\t\n\n\n\nCIRCLE");
circle(120,270,30);
printf("\t\n\n\n\nECLIPSE");
ellipse(120,350,0,360,30,20);
getch();
Output:
Write a Program to draw animation using increasing circles filled with different colors and
patterns.
#include<graphics.h>
#include<conio.h>
void main()
x=getmaxx()/3;
y=getmaxx()/3;
setbkcolor(WHITE);
setcolor(BLUE);
for(i=1;i<=8;i++)
setfillstyle(i,i);
delay(20);
circle(x, y, i*20);
floodfill(x-2+i*20,y,BLUE);
getch();
closegraph();
}
Output:
Colors in C Graphics Programming
There are 16 colors declared in graphics.h header file. We use colors to set the current drawing
color, change the color of background, change the color of text, to color a closed shape etc
(Foreground and Background Color). To specify a color, we can either use color constants like
setcolor(RED), or their corresponding integer codes like setcolor (4). Below is the color code in
increasing order.
CONSTANT VALUE
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
BLINK 16
Graphics example using color
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
setcolor(BLUE);
//Draw an object. For this example,drawing a rectangle using the rectangle function
rectangle(50,50,100,100);
getch();
closegraph();
}
Hut Graphics
#include<graphics.h>
#include<conio.h>
void main(){
int gd = DETECT,gm;
/* Draw Hut */
setcolor(WHITE);
rectangle(150,180,250,300);
rectangle(250,180,420,300);
rectangle(180,250,220,300);
line(200,100,150,180);
line(200,100,250,180);
line(200,100,370,100);
line(370,100,420,180);
/* Fill colours */
setfillstyle(SOLID_FILL, BROWN);
setfillstyle(SLASH_FILL, BLUE);
setfillstyle(HATCH_FILL, GREEN);
getch();
closegraph();
Output:
File Handling in C:
A file is a place on the disk where a group of related data is stored. File handling in C enables us
to create, update, read, and delete the files stored on the local file system through our C
program. The following operations can be performed on a file.
Functions for file handling: There are many functions in the C library to open, read, write,
search and close the file. A list of file functions are given below:
We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
FILE *file_ponter;
File_pointer=fopen(“filename”,”mode”);
The first statement declares the variable file_ponter as a pointer to the type FILE. FILE is a
structure that is defined in the I/O library.
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.txt".
o The mode in which the file is to be opened. It is a string.
Mode Description
#include<stdio.h>
#include<conio.h>
void main( )
FILE *fp ;
char ch ;
fp = fopen("mca.txt","w") ;
fputc(ch,fp);
fclose(fp);
fp=fopen("mca.txt","r");
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose (fp ) ;
getch();
}
Use of fprintf() and fscanf() functions:
#include<stdio.h>
#include<conio.h>
void main( )
FILE *fp;
char buff[255];
fclose(fp);
fp = fopen("mca1.txt", "r");
getch();
}
Use of fseek() and ftell() function:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
int length;
fp = fopen("myfile.txt","w");
length = ftell(fp);
fclose(fp);
getch();
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
Output: