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

C-Unit-5

This document covers dynamic memory allocation in C, detailing functions like malloc, calloc, realloc, and free, along with their usage and advantages. It also introduces file handling in C, including file operations, types, and the fopen() function for opening files. The document emphasizes the importance of dynamic memory management for flexible data structures and file manipulation in programming.

Uploaded by

amitmaurya70688
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C-Unit-5

This document covers dynamic memory allocation in C, detailing functions like malloc, calloc, realloc, and free, along with their usage and advantages. It also introduces file handling in C, including file operations, types, and the fopen() function for opening files. The document emphasizes the importance of dynamic memory management for flexible data structures and file manipulation in programming.

Uploaded by

amitmaurya70688
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

2/20/2023

UNIT - V
Dynamic Memory Allocation: Introduction, Library functions –
PROBLEM SOLVING USING C malloc, calloc, realloc and free.
KCA102
UNIT-V File Handling: Basics, File types, File operations, File pointer,
MCA I YEAR, I SEM. File opening modes, File handling functions, File handling
through command line argument, Record I/O in files.

Graphics: Introduction, Constant, Data types and global


variables used in graphics, Library functions used in drawing,
Drawing and filling images, GUI interaction within the program.

1 2

UNITED INSTITUTE OF MANAGEMENT, NAINI MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

TWO TYPES OF MEMORY ALLOCATIONS Dynamic Memory Allocation In C:


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

Compile Time Run Time


3 4

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

1
2/20/2023

What is static memory allocation in C? Why do we need dynamic memory allocation?


Static variable defines in one block of allocated space, of a Dynamic allocation is required when you don't know the worst
fixed size. Once it is allocated, it can never be freed. Memory is case requirements for memory. Then, it is impossible to
allocated for the declared variable in the program. In this statically allocate the necessary memory, because you don't
allocation, once the memory is allocated, the memory size know how much you will need. Even if you know the worst case
cannot change. requirements, it may still be desirable to use dynamic memory
allocation.
Example-
int a;
Static Memory Allocate
int a[5];
struct emp p1[5];

5 6

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Advantages of Dynamic memory allocation: Dynamic Memory Allocation


Data structures can grow and shrink according to the
requirement. We can allocate (create) additional storage Static Memory Allocation Dynamic Memory Allocation
whenever we need them. We can de-allocate (free/delete)
Memory is allocated at compile time. memory is allocated at run time.
dynamic space whenever we are. done with them.
Dynamic Allocation is done at run time. memory can't be increased while memory can be increased while
executing program. executing program.

used in array. used in linked list.

7 8

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

2
2/20/2023

Dynamic memory allocation: Example-1-Dynamic memory allocation


#include <stdio.h>
Description #include <stdlib.h>
The C library function void *malloc(size_t size) allocates the requested int main ()
memory and returns a pointer to it. { OUTPUT
char *str; String = tutorialspoint, Address = 355090448
/* Initial memory allocation */ String = tutorialspoint.com, Address = 355090448
Declaration
void *malloc(size_t size) str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
Parameters printf("String = %s, Address = %u\n", str, str);
/* Reallocating memory */
size − This is the size of the memory block, in bytes.
str = (char *) realloc(str, 25);
strcat(str, ".com");
Return Value
printf("String = %s, Address = %u\n", str, str);
This function returns a pointer to the allocated memory, or NULL if
free(str);
the request fails.
return(0);
}
9 10

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

malloc() method: C malloc() method


The “malloc” or “memory allocation” method in C is used to Continue…
dynamically allocate a single large block of memory with the specified
size.
It returns a pointer of type void which can be cast into a pointer of any
form.
It doesn’t Initialize memory at execution time so that it has initialized
each block with the default garbage value initially.
Syntax:
ptr = (cast-type*) malloc(byte-size);
or
(void*)malloc(byte-size);

For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory. 11 12

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

3
2/20/2023

Example 1- Memory Allocation


C malloc() method
Continue… #include <stdio.h> // Dynamically allocate memory using malloc()
#include <stdlib.h> ptr = (int*)malloc(n * sizeof(int));

int main() // Check if the memory has been successfully


{ // allocated by malloc or not
if (ptr == NULL) {
// This pointer will hold the printf("Memory not allocated.\n");
// base address of the block created exit(0);
int* ptr; }
int n, i; else
{
// Get the number of elements for the array // Memory has been successfully allocated
printf("Enter number of elements:"); printf("Memory successfully allocated using
scanf("%d",&n); malloc.\n");
printf("Entered number of elements: %d\n",
n);

13 14

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Continue…
calloc() method:
// Get the elements of the array “calloc” or “contiguous allocation” method in C is used to
for (i = 0; i < n; ++i) dynamically allocate the specified number of blocks of memory of the
{ specified type. it is very much similar to malloc() but has two different
ptr[i] = i + 1;
} points and these are:
It initializes each block with a default value ‘0’.
// Print the elements of the array It has two parameters or arguments as compare to malloc().
printf("The elements of the array are: "); It creates multiple block with same size.
for (i = 0; i < n; ++i)
{ Output: Syntax:
printf("%d, ", ptr[i]); Enter number of elements: 5
} Memory successfully allocated using malloc.
}
ptr = (cast-type*)calloc(n, element-size);
The elements of the array are: 1, 2, 3, 4, 5,
return 0;
} here, n is the no. of elements and element-size is the size of
each element.

15 16

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

4
2/20/2023

Conti… Example-1 – realloc():


ptr = (float*) calloc(25, sizeof(float)); #include <stdio.h> printf("Building and calculating the
int main() sequence sum of the first 10 terms
This statement allocates contiguous space in memory for 25 { \ n ");
elements each with the size of the float. int i, * ptr, sum = 0; for (i = 0; i < 10; ++i)
ptr = calloc(10, sizeof(int)); {
if (ptr == NULL) *(ptr + i) = i;
{ sum += * (ptr + i);
printf("Error! memory not }
allocated."); printf("Sum = %d", sum);
exit(0); free(ptr);
} return 0;
}
OUTPUT-
Building and calculating the sequence sum of the first 10 terms
Sum = 45
17 18

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5


4 | C PROGRAMMING MR. ASHUTOSH PANDEY

realloc() method:
Syntax:
 Using the C realloc() function, you can add more memory size
to already allocated memory. It expands the current block ptr = realloc (ptr , newsize);
while leaving the original content as it is. realloc() in C stands
for reallocation of memory.  The above statement allocates a new memory space with a
 realloc() can also be used to reduce the size of the previously specified size in the variable newsize. After executing the
allocated memory. function, the pointer will be returned to the first byte of the
memory block.
 The new size can be larger or smaller than the previous
Syntax: memory. We cannot be sure that if the newly allocated block
will point to the same location as that of the previous memory
ptr = realloc (ptr , newsize); block. This function will copy all the previous data in the new
region. It makes sure that data will remain safe.

19 20

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

5
2/20/2023

Example -1:
Example-2 -Dynamic Arrays in C:
#include <stdio.h>
int main () #include <stdio.h>
{ int main()
char *ptr; {
ptr = (char *) malloc(10); //memory allocation int * arr_dynamic = NULL;
strcpy(ptr, "Programming"); int elements = 2, i;
printf("String=%s, Address = %u\n", ptr, ptr); arr_dynamic = calloc(elements, sizeof(int)); //Array with 2 integer blocks
ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size for (i = 0; i < elements; i++)
strcat(ptr, " In 'C'"); arr_dynamic[i] = i;
printf(“String= %s, Address = %u\n", ptr, ptr); for (i = 0; i < elements; i++)
free(ptr); printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]);
return 0; Note- Whenever the realloc() in C results in an unsuccessful
} operation, it returns a null pointer, and the previous data is
also freed. 21 22

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

free()-
Continue…
The free() function in C library allows you to release or
elements = 4; deallocate the memory blocks which are previously allocated by
arr_dynamic = realloc(arr_dynamic, elements * sizeof(int)); calloc(), malloc() or realloc() functions. It frees up the memory
//reallocate 4 elements blocks and returns the memory to heap. It helps freeing the
printf("After realloc\n"); OUTPUT- memory in your program which will be available for later use.
for (i = 2; i < elements; i++) Syntax-
arr_dynamic[0]=0 #include <stdio.h>
arr_dynamic[i] = i; void free(void *ptr)
arr_dynamic[1]=1 int main()
for (i = 0; i < elements; i++) {
printf("arr_dynamic[%d]=%d\n", i, arr_dynamic[i]); After realloc int* ptr = malloc(10 * sizeof(*ptr));
free(arr_dynamic); if (ptr != NULL){ *(ptr + 2) = 50;
arr_dynamic[0]=0 printf("Value of the 2nd integer is %d",*(ptr + 2));
} arr_dynamic[1]=1
}
arr_dynamic[2]=2
free(ptr);
arr_dynamic[3]=3
}
23 24

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

6
2/20/2023

SUMMERY-

 We can dynamically manage memory by creating memory blocks as needed


in the heap
 In C Dynamic Memory Allocation, memory is allocated at a run time.
 Dynamic memory allocation permits to manipulate strings and arrays whose
size is flexible and can be changed anytime in your program.
 It is required when you have no idea how much memory a particular
structure is going to occupy. File Handling in C
 Malloc() in C is a dynamic memory allocation function which stands for
memory allocation that blocks of memory with the specific size initialized
to a garbage value
 Calloc() in C is a contiguous memory allocation function that allocates
multiple memory blocks at a time initialized to 0.
 Realloc() in C is used to reallocate memory according to the specified size.
 Free() function is used to clear the dynamically allocated memory. 25 26

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

File Handling in C-
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.

 Creation of the new file


 Opening an existing file
 Reading from the file
 Writing to the file
 Deleting the file
27 28

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

7
2/20/2023

Functions for File Handling in C 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 *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:

 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.ext".
 The mode in which the file is to be opened. It is a string.
29 30

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

fopen() function Important:

Difference between exit(1) , exit(0) & exit()-

31 32

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

8
2/20/2023

Writing File : fprintf() function:


The fopen function works in the following way.
The fprintf() function is used to write set of characters into
file. It sends formatted output to a stream.
 Firstly, It searches the file to be opened.
SYNTAX-
 Then, it loads the file from the disk and place it into the int fprintf(FILE *stream, const char *format [, argument, ...])
buffer. The buffer is used to provide efficiency for the read
operations. #include <stdio.h>
main()
 It sets up a character pointer which points to the first {
character of the file. FILE *fp;
fp = fopen("file.txt", "w");//opening file
 If the file is successfully opened, it returns file pointer, if fprintf(fp, "Hello file by fprintf...\n");//writing data into file
not it returns NULL. fclose(fp);//closing file
33
} 34

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Reading File Data Character by Character. Reading File - fscanf() function:


The fscanf() function is used to read set of characters from
file. It reads a word from the file and returns EOF at the end
#include<stdio.h>
void main( ) of file.
{ SYNTAX-
FILE *fp ; int fscanf(FILE *stream, const char *format [, argument, ...])
char ch ;
fp = fopen("file_handle.c","r") ; #include <stdio.h>
while ( 1 ) main()
{ {
ch = fgetc ( fp ) ;
OUTPUT-
The content of the file will be printed. FILE *fp;
if ( ch == EOF )
break ; char buff[255];//creating char array to store data of file
printf("%c",ch) ; fp = fopen("file.txt", "r");
} while(fscanf(fp, "%s", buff)!=EOF){
fclose (fp ) ; printf("%s ", buff );
}
35
} 36
fclose(fp);
UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY }

9
2/20/2023

C File Example: Storing employee information printf("Enter the id\n");


Let's see a file handling example to store employee
scanf("%d", &id);
information as entered by user from console. We are going
fprintf(fptr, "Id= %d\n", id);
to store id, name and salary of the employee.
printf("Enter the name \n");
#include <stdio.h> scanf("%s", name);
void main() fprintf(fptr, "Name= %s\n", name);
{
FILE *fptr; printf("Enter the salary\n");
int id; scanf("%f", &salary);
char name[30]; fprintf(fptr, "Salary= %.2f\n", salary);
float salary; fclose(fptr);
fptr = fopen("emp.txt", "w+");/* open for writing */ }
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
37 38

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Writing File : fputc() function- Reading File : fgetc() function-


The fputc() function is used to write a single character into file. The fgetc() function returns a single character from the file. It
It outputs a character to a stream. gets a character from the stream. It returns EOF at the end of
file.
Syntax-
int fputc(int c, FILE *stream) Syntax-
int fgetc(FILE *stream)
#include <stdio.h>
main() #include<stdio.h> while((c=fgetc(fp))!=EOF)
{ #include<conio.h> {
FILE *fp; void main() printf("%c",c);
fp = fopen("file1.txt", "w");//opening file { }
fputc('a',fp);//writing single character into file FILE *fp; fclose(fp);
fclose(fp);//closing file char c; getch();
} clrscr(); }
39
fp=fopen("myfile.txt","r"); 40

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

10
2/20/2023

Delete File in C-
Write string into a file : fputs() function- The remove function in C can be used to delete a file. The
function returns 0 if files is deleted successfully, other returns a
non-zero value.
Using remove() function in C, we can write a program which can
destroy itself after it is compiled and executed.
#include<stdio.h>
int main()
{
if (remove("abc.txt") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");
return 0;
41
} 42

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Command Line Arguments in C- Example-Command Line Arguments in C.


The arguments passed from command line are called command
// The program name is cl.c
line arguments. These arguments are handled by main()
#include<stdio.h>
function.
int main(int argc, char** argv)
To support command line argument, you need to change the
{
structure of main() function as given below.
printf("Welcome to DataFlair tutorials!\n\n");
int i;
Syntax-
printf("The number of arguments are: %d\n",argc);
int main(int argc, char *argv[] )
printf("The arguments are:");
for ( i = 0; i < argc; i++)
Here, argc counts the number of arguments. It counts the file
{
name as the first argument.
printf("%s\n", argv[i]);
}
The argv[] contains the total number of arguments. The first
return 0;
argument is the file name always.
43
} 44

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

11
2/20/2023

Graphics in C-

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 like jumping ball and moving cars.
Graphics in C
The first step in any graphics program is to initialize the
graphics drivers on the computer using initgraph method
of graphics.h library.

void initgraph(int *graphicsDriver, int *graphicsMode, char


45 *driverDirectoryPath); 46

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

void initgraph(int *graphicsDriver, int *graphicsMode, char void initgraph(int *graphicsDriver, int *graphicsMode,
*driverDirectoryPath); char *driverDirectoryPath);
Graphics Driver : It is a pointer to an integer specifying
It initializes the graphics system by loading the passed the graphics driver to be used. It tells the compiler that
graphics driver then changing the system into graphics what graphics driver to use or to automatically detect the
mode. It also resets or initializes all graphics settings like drive. In all our programs we will use DETECT macro of
color, palette, current position etc, to their default values. graphics.h library that instruct compiler for auto detection
of graphics driver.

Graphics Mode : It is a pointer to an integer that


specifies the graphics mode to be used. If *graphdriver is
set to DETECT, then initgraph sets *graphmode to the
highest resolution available for the detected driver.
47 48

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

12
2/20/2023

void initgraph(int *graphicsDriver, int *graphicsMode, Colors in C Graphics Programming-


char *driverDirectoryPath);
There are 16 colors declared in C Graphics. We use
colors to set the current drawing color, change the color of
Driver Directory Path : It specifies the directory path
background, change the color of text, to color a closed
where graphics driver files (BGI files) are located. If
shape etc.
directory path is not provided, then it will seach for driver
files in current working directory directory. In all our
To specify a color, we can either use color constants like
sample graphics programs, you have to change path of
setcolor(RED), or their corresponding integer codes like
BGI directory accordingly where you turbo C compiler is
setcolor(4). Below is the color code in increasing order.
installed.

49 50

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Colors in C Graphics Programming- Colors in C Graphics Programming-

COLOR MACRO INTEGER VALUE COLOR MACRO INTEGER VALUE


BLACK 0 LIGHTBLUE 9
BLUE 1 LIGHTGREEN 10
GREEN 2 LIGHTCYAN 11
CYAN 3 LIGHTRED 12
RED 4 LIGHTMAGENTA 13
MAGENTA 5 YELLOW 14
BROWN 6 WHITE 15
LIGHTGRAY 7
Note- At the end of our graphics program, we have to
DARKGRAY 8
unloads the graphics drivers and sets the screen back to text
51 mode by calling closegraph function. 52

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

13
2/20/2023

Here is our first C Graphics program to draw a C Program to Draw a Circle Using C Graphics
straight line on screen.
Function Description
initgraph It initializes the graphics system by loading the passed
/* C graphics program to draw a line */ graphics driver then changing the system into graphics
#include<graphics.h> mode.
#include<conio.h> getmaxx It returns the maximum X coordinate in current graphics
int main() { mode and driver.
int gd = DETECT, gm;
getmaxy It returns the maximum Y coordinate in current graphics
/* initialization of graphic mode */ mode and driver.
initgraph(&gd, &gm, "C:\\TC\\BGI");
outtextxy It displays a string at a particular point (x,y) on screen.
line(100,100,200, 200);
getch(); circle It draws a circle with radius r and centre at (x, y).
closegraph();
closegraph It unloads the graphics drivers and sets the screen back to
return 0; text mode.
} 53 54

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

C Program to Draw a Circle Using C Graphics C program to draw rectangle and bar using graphics
#include<stdio.h> #include<stdio.h>
#include<graphics.h> #include<graphics.h>
#include<conio.h> #include<conio.h>
int main()
int main(){ {
int gd = DETECT,gm; int gd = DETECT,gm;
int x ,y ,radius=80; initgraph(&gd, &gm, "C:\\TC\\BGI");
initgraph(&gd, &gm, “BGI");
/* Initialize center of circle with center of screen */
/* Draw rectangle on screen
x = getmaxx()/2; rectangle(int left, int top, int right, int bottom);*/
y = getmaxy()/2; rectangle(150, 50, 400, 150);
outtextxy(x-100, 50, “ASHU");
/* Draw circle on screen */ /* Draw Bar on screen */
circle(x, y, radius); bar(150, 200, 400, 350);
getch();
closegraph(); getch();
return 0; closegraph();
} return 0;
55 } 56

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

14
2/20/2023

Write a Program to draw basic graphics construction like Write a Program to draw basic graphics construction like
line, circle, arc, ellipse and rectangle line, circle, arc, ellipse and rectangle
#include<graphics.h>
#include<conio.h>
void main()
{
intgd=DETECT,gm; initgraph (&gd,&gm,”bgi");
setbkcolor(GREEN);
printf("\t\t\t\n\nLINE");
line(50,40,190,40); // line(int x1, int y1, int x2, int y2)
printf("\t\t\n\n\n\nRECTANGLE");
rectangle(125,115,215,165); //rectangle(int left, int top, int right, int bottom);
printf("\t\t\t\n\n\n\n\n\n\nARC");
arc(120,200,180,0,30); // arc(int x, int y, int start_angle, int end_angle, int radius);
printf("\t\n\n\n\nCIRCLE");
circle(120,270,30); // circle(int x, int y, int radius)
printf("\t\n\n\n\nECLIPSE");
ellipse(120,350,0,360,30,20);
getch(); } 57 58

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Text Functions-
setcolor(): It will set the cursor color and hence anything written
on the output screen will be of the color as per setcolor().
function prototype :
setcolor(int)

settexttyle(): It set the text font style, its orientation(horizontal/


vertical) and size of font.
Function prototype :
settextstyle(int style, int orientation, int size);

outtextxy() : It will print message passed to it at some certain


coordinate (x,y).
function prototype :
settextstyle(int style, int orientation, int size); 59 60

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

15
2/20/2023

getbkcolor() & setbkcolor() setfillstyle() and floodfill() in C


The header file graphics.h contains setfillstyle() function which
int getbkcolor(void) sets the current fill pattern and fill color.
As getbkcolor() returns an integer value corresponding to the floodfill() function is used to fill an enclosed area. Current fill
background color, so below is the table for Color values. pattern and fill color is used to fill the area.

setbkcolor(GREEN) Syntax :
The setbkColor function sets the current background color to void setfillstyle(int pattern, int color)
the specified color value, or to the nearest physical color if the void floodfill(int x, int y, int border_color)
device cannot represent the specified color value.

61 62

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

setfillstyle() and floodfill() in C setfillstyle() and floodfill() in C


// C Implementation for setfillstyle
// and floodfill function
#include <graphics.h> // x and y is a position and
int main() // radius is for radius of circle Output-
{ circle(x_circle,y_circle,radius);
int gd = DETECT, gm; // fill the color at location
initgraph(&gd, &gm, " "); // (x, y) with in border color
// center and radius of circle floodfill(x_circle,y_circle,border_color);
int x_circle = 250; getch();
int y_circle = 250; closegraph();
int radius=100; return 0;
// setting border color }
int border_color = WHITE;
// set color and pattern
setfillstyle(HATCH_FILL,RED); 63 64

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

16
2/20/2023

Print colored message with different fonts and sizes in C. Print colored message with different fonts and sizes in C.

// C program to print for (i=3; i<7; i++)


// message as colored characters {
#include<stdio.h> // setcolor of cursor
#include<graphics.h> setcolor(i);
#include<dos.h> // set text style as
// function for printing // settextstyle(font, orientation, size)
// message as colored character settextstyle(i,0,i);
void printMsg() // print text at coordinate x,y;
{ outtextxy(100,20*i,"Geeks");
// auto detection delay(500);
int gdriver = DETECT,gmode,i; }
delay(2000);
// initialize graphics mode }
initgraph(&gdriver,&gmode, "BGI"); 65 66

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Print colored message with different fonts and sizes in C. Read Image File in C Graphics

// driver program
void main()
{
printMsg();
} Output-

The function initializes the graphics system by opening a


graphics window of the specified size. The first two
parameters (width and height) are required, but all other
parameters have default values.
The title parameter is the title that will be printed at the top of
the window (with a default of "Windows BGI".)
67 68

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

17
2/20/2023

C program to draw pie chart using graphics


#include <graphics.h> //creating bars with certain filling style
#include <conio.h>
#include <dos.h> setfillstyle(LINE_FILL,RED);
#include <stdlib.h> bar(150,200,200,419);

void main() { setfillstyle(LINE_FILL,GREEN);


bar(225,90,275,419);
int graphicdriver=DETECT,graphicmode;
setfillstyle(LINE_FILL,BLUE);
//calling initgraph function with bar(300,120,350,419);
//certain parameters
initgraph(&graphicdriver,&graphicmode,”bgi"); setfillstyle(LINE_FILL,YELLOW);
bar(375,180,425,419);
//Printing message for user
outtextxy(10, 10 + 10, “Draw a bar chart."); getch();
closegraph();
//initilizing lines for x and y axis }
line(100,420,100,60);
line(100,420,500,420); 69 70

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Exercise1- #include<graphics.h>
#include<conio.h>
Write a Program to draw animation using increasing circles void main()
filled with different colors and patterns. {
intgd=DETECT, gm, i, x, y;
initgraph(&gd, &gm, "C:\\TC\\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();
71 closegraph(); 72

}
UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

18
2/20/2023

Exercise2- // C program to create a smiley face


#include <conio.h> // Set color of background to black
setcolor(BLACK);
Draw a smiley face using Graphics in C language. #include <dos.h>
setfillstyle(SOLID_FILL, BLACK);
#include <graphics.h>
#include <stdio.h> // Use fill ellipse for creating eyes
int main() fillellipse(310, 85, 2, 6);
{ fillellipse(290, 85, 2, 6);

int gr = DETECT, gm; // Use ellipse for creating mouth


ellipse(300, 100, 205, 335, 20, 9);
initgraph(&gr, &gm, "BGI"); ellipse(300, 100, 205, 335, 20, 10);
ellipse(300, 100, 205, 335, 20, 11);
// Set color of smiley to yellow
getch();
setcolor(YELLOW); closegraph();

// creating circle and fill it with return 0;


// yellow color using floodfill. }
circle(300, 100, 40);
73 setfillstyle(SOLID_FILL, YELLOW); 74

floodfill(300, 100, YELLOW);


UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

Page1-
Exercise3-
// C++ program to draw the moving // Move the cycle
// cycle using computer graphics for (i = 0; i < 600; i++) {
Draw a moving cycle using computer graphics #include <conio.h> // Upper body of cycle
#include <dos.h> line(50 + i, 405, 100 + i, 405);
programming in C. #include <graphics.h> line(75 + i, 375, 125 + i, 375);
#include <iostream.h> line(50 + i, 405, 75 + i, 375);
line(100 + i, 405, 100 + i, 345);
// Driver code line(150 + i, 405, 100 + i, 345);
int main() line(75 + i, 345, 75 + i, 370);
{ line(70 + i, 370, 80 + i, 370);
int gd = DETECT, gm, i, a; line(80 + i, 345, 100 + i, 345);

// Path of the program // Wheel


initgraph(&gd, &gm, "BGI"); circle(150 + i, 405, 30);
circle(50 + i, 405, 30);

75 76

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

19
2/20/2023

Page2-
Exercise4-
// Road
line(0, 436, getmaxx(), 436); Write a Program to make a moving colored car
// Stone
rectangle(getmaxx() - i, 436,650 - i, 431);
using inbuilt functions.
// Stop the screen for 10 secs
delay(10);
// Clear the screen
cleardevice();
}
getch();
// Close the graph
closegraph();
}

77 78

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY

#include<graphics.h> circle(28+i, cy+15, 10);


#include<conio.h> line(38+i, cy+15, 102+i, cy+15);
circle(112+i, cy+15,10);
int main()
{
intgd=DETECT,gm, i, maxx, cy;
line(122+i, cy+15 ,140+i,cy+15);
line(140+i, cy+15, 140+i, cy-20);
rectangle(50+i, cy-62, 90+i, cy-30);
END OF UNIT-V
initgraph(&gd, &gm, "C:\\TC\\BGI"); setfillstyle(1,BLUE);
setbkcolor(WHITE); setcolor(RED); floodfill(5+i, cy-15, RED);
maxx = getmaxx(); setfillstyle(1, LIGHTBLUE); PROBLEM SOLVING USING C
cy = getmaxy()/2; floodfill(52+i, cy-60, RED);
delay(10);
KCA102
for(i=0;i<maxx-140;i++)
{ } UNIT-V
cleardevice(); getch();
closegraph(); MCA I YEAR, I SEM.
line(0+i,cy-20, 0+i, cy+15);
return 0;
line(0+i, cy-20, 25+i, cy-20); }
line(25+i, cy-20, 40+i, cy-70);
line(40+i, cy-70, 100+i, cy-70);
line(100+i, cy-70, 115+i, cy-20);
line(115+i, cy-20, 140+i, cy-20);
line(0+i, cy+15, 18+i, cy+15); 79 80

UNIT – 5 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 4 | C PROGRAMMING MR. ASHUTOSH PANDEY

20

You might also like