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

Problem Solving Using C (Unit 5)

This program draws an animation of increasing circles by: 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Problem Solving Using C (Unit 5)

This program draws an animation of increasing circles by: 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Dynamic memory allocation:

The concept of dynamic memory allocation in c language enables the C programmer to


allocate memory at runtime. Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.

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.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program. program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc() reallocates the memory occupied by malloc() or calloc() functions.

free() frees the dynamically allocated memory.


malloc() function in C:

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

Let's see the example of malloc() function.

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

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

in above example replace only this following instruction with malloc():

ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc

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.

Let's see the syntax of realloc() function.

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;

ptr= (int *)realloc(ptr, sizeof(int)*3);


*(ptr + 2) = 30;
for(i = 0; i < 3; i++)
printf("%d ", *(ptr + i));

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.

Let's see the syntax of free() function.

free(ptr);
Graphics:

Graphics programming in C used to drawing various geometrical shapes (rectangle, circle


eclipse etc), use of mathematical function in drawing curves, coloring an object with different
colors and patterns and simple animation programs.

First graphics program (Draw a line)

#include<graphics.h>

#include<stdio.h>

#include<conio.h>

void main()

int gdriver = DETECT, gmode;

int x1 = 200, y1 = 200;

int x2 = 300, y2 = 300;

clrscr();

initgraph(&gdriver, &gmode,"C:\\TURBOC3\\BGI");

line(x1, y1, x2, y2);

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.

void initgraph(int *graphicsDriver, int *graphicsMode, char *driverDirectoryPath);

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.

graphicsMode : It is a pointer to an integer that specifies the graphics mode to be used. If


*gdriver is set to DETECT, then initgraph sets *gmode to the highest resolution available for the
detected 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.

BGI is accessible in C/C++ with graphics.lib/graphics.h.

We have declared variables so that we can keep track of starting and ending point.

int x1=200, y1=200;

int x2=300, y2=300;

No, We need to pass just 4 parameters to the line function.

line(x1,y1,x2,y2);

line Function Draws Line From (x1,y1) to (x2,y2) .

Syntax : line(x1,y1,x2,y2);

Parameter Explanation

x1 - X Co-ordinate of First Point

y1 - Y Co-ordinate of First Point

x2 - X Co-ordinate of Second Point

y2 - Y Co-ordinate of Second Point

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:

line(): This function draws a line in the graphics mode.

void line(int startx, int starty, int endx, int endy)

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.

void bar(int left, int top, int right, int bottom)

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.

void circle(int x, int y, int radius)

drawpoly(): This function draws an outline of a polygon.

void drawpoly(int numpoints, int far *points)

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.

ellipse(): Draws an ellipse using the current drawing color.

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.

void floodfill(int x, int y, int border)

outtext(): Displays the text at a specified position in graphics mode.

void outtext(int x, int y, char *str)

putpixel(): Prints a pixel at the specified point on the screen.

void putpixel(int x, int y, int color)

rectangle(): Draws a rectangular box on the screen using the points given in the parameters.

void rectangle(int left, int top, int right, int bottom)

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

int gd=DETECT, gm, i, x, y;

initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

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 the graphics header file

#include<graphics.h>

#include<stdio.h>

#include<conio.h>

void main()

//Initialize the variables for the graphics driver and mode

int gd = DETECT, gm;

clrscr();

initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

//Set the color of the object you want to draw.

setcolor(BLUE);

//Draw an object. For this example,drawing a rectangle using the rectangle function

rectangle(50,50,100,100);

getch();

//unloads the graphics drivers

closegraph();

}
Hut Graphics

#include<graphics.h>

#include<conio.h>

void main(){

int gd = DETECT,gm;

initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

/* 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);

floodfill(152, 182, WHITE);

floodfill(252, 182, WHITE);

setfillstyle(SLASH_FILL, BLUE);

floodfill(182, 252, WHITE);

setfillstyle(HATCH_FILL, GREEN);

floodfill(200, 105, WHITE);


floodfill(210, 105, WHITE);

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.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the 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:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file


Opening File: fopen():

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.

The fopen() function accepts two parameters:

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.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a file in read mode if it exist.

w opens or creates the file in write mode.

a opens or creates the file in append mode.

Ex: WAP to write and read data from a text file.


Use of fputc() and fgetc() functions:

#include<stdio.h>

#include<conio.h>

void main( )

FILE *fp ;

char ch ;

fp = fopen("mca.txt","w") ;

while ((ch=getchar())!=EOF) //ctr+z means EOF

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

fp = fopen("mca1.txt", "w");//opening file

fprintf(fp, "Hello file by fprintf...\n");//writing data into file

fclose(fp);

fp = fopen("mca1.txt", "r");

while(fscanf(fp, "%s", buff)!=EOF)

printf("%s ", buff );

getch();

}
Use of fseek() and ftell() function:

There are 3 constants used in the fseek() function for whence:

SEEK_SET (Beginning of file)

SEEK_CUR (Current position of the file pointer)

SEEK_END (End of file)

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

int length;

fp = fopen("myfile.txt","w");

fprintf(fp,"welcome in file handling");

fseek( fp, 8, SEEK_SET );

fprintf(fp,"Amit kumar Shukla");

length = ftell(fp);

printf("Size of file: %d bytes", length);

fclose(fp);

getch();

Output: Size of file:25 bytes

Content of file will be: welcome Amit Kumar Shukla


Use of rewind() function:

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

rewind(fp);//moves the file pointer at beginning of the file

while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}

fclose(fp);
getch();
}

Output:

this is a simple textthis is a simple text

You might also like