Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Unit–5 problem solving c

Unit-5-Problem Solving Using C pdf

Uploaded by

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

Unit–5 problem solving c

Unit-5-Problem Solving Using C pdf

Uploaded by

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

Unit – 5 dynamic memoryallocation in C programming.

They are:
Problem Solving Using C (MCA-112) 1. malloc() initializes each block with default garbage value
Dynamic Memory Allocation: Introduction, Library 2. calloc() initializes each block with zero value
3. free() dynamically de-allocate the memory by freeing allocated space
functions –malloc, calloc, realloc and free. 4. realloc() dynamically re-allocate memory with default garbage value
File Handling: Basics, File types, File operations, File pointer, 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.

Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()

Since C is a structured language, it has some fixed rules for programming.


One ofit includes changing the size of an array. An array is collection of
items stored at continuous memory locations.

As it can be seen that the length (size) of the array above made is 9. But
what ifthere is a requirement to change this length (size). For Example,
 If there is a situation where only 5 elements are needed to be entered in
this array. In this case, the remaining 4 indices are just wasting memory
in this array. So there is a requirement to lessen the length (size) of the
array from 9 to5.
 Take another situation. In this, there is an array of 9 elements with all 9
indicesfilled. But there is a need to enter 3 more elements in this array.
In this case 3 indices more are required. So the length (size) of the
array needs to be changedfrom 9 to 12.
This problem is solved in C through Dynamic Memory Allocation.

Therefore, C Dynamic Memory Allocation can be defined as a procedure


in which the size of a data structure (like Array) is changed during the
runtime.
C provides some functions to achieve these tasks. There are 4 library
functions provided by C defined under <stdlib.h> header file to facilitate
C malloc() method // Get the number of elements for the
“malloc” or “memory allocation” method in C is used to dynamically arrayn = 5;
allocate a single large block of memory with the specified size. It returns ///////int arr[n];
a pointer of type void which can be cast into a pointer of any form. It printf("Enter number of elements: %d\n", n);
initializes each block with default garbage value.
Syntax: // Dynamically allocate memory using
ptr = (cast-type*) malloc(byte-size) malloc()ptr = (int*) malloc(n * sizeof(int));
For Example:
ptr = (int*) malloc(100 * sizeof(int)); // Check if the memory has been successfully
// allocated by malloc or
Since the size of int is 4 bytes, this statement will allocate 400 bytes of notif (ptr == NULL) {
memory.And, the pointer ptr holds the address of the first byte in the printf("Memory not
allocated memory. allocated.\n");exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using
malloc.\n");

// Get the elements of the


arrayfor (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are:
If space is insufficient, allocation fails and returns a NULL ");for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
pointer.Example: }
#include }
<stdio.h>
#include return 0;
<stdlib.h> int }
main()
Output:
{
Enter number of elements: 5
// This pointer will hold the
Memory successfully allocated using
// base address of the block
malloc.The elements of the array are: 1,
createdint* ptr;
2, 3, 4, 5,
int n, i;
int n, i;

// Get the number of elements for the


calloc() method arrayn = 5;
“calloc” or “contiguous allocation” method in C is used to dynamically printf("Enter number of elements: %d\n", n);
allocate the specified number of blocks of memory of the specified
type. Itinitializes each block with a default value ‘0’. // Dynamically allocate memory using
Syntax: calloc()ptr = (int*) calloc(n, sizeof(int));
ptr = (cast-type*)calloc(n, element-size);
For Example: // Check if the memory has been successfully
ptr = (float*) calloc(25, sizeof(float)); // allocated by calloc or
notif (ptr == NULL) {
This statement allocates contiguous space in memory for 25 elements printf("Memory not
each withthe size of the float. allocated.\n");exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using
calloc.\n");
// Get the elements of the
arrayfor (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are:
");for (i = 0; i < n; ++i) {
If space is insufficient, allocation fails and returns a NULL pointer. printf("%d, ", ptr[i]);
Example: }
#include }
<stdio.h>
#include return 0;
<stdlib.h> }
Output:
int main() Enter number of elements: 5
{ Memory successfully allocated using
calloc.The elements of the array are: 1,
// This pointer will hold the 2, 3, 4, 5,
// base address of the block
createdint* ptr;
n = 5;
printf("Enter number of elements: %d\n", n);
C free() method // Dynamically allocate memory using
“free” method in C is used to dynamically de-allocate the memory. malloc()ptr = (int*)malloc(n * sizeof(int));
The memory allocated using functions malloc() and calloc() is not de-
allocated ontheir own. Hence the free() method is used, whenever the // Dynamically allocate memory using
dynamic memory allocation takes place. It helps to reduce wastage of calloc()ptr1 = (int*)calloc(n, sizeof(int));
memory by freeing it.
Syntax: // Check if the memory has been successfully
free(ptr); // allocated by malloc or not
if (ptr == NULL || ptr1 == NULL)
{ printf("Memory not
allocated.\n");exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using
malloc.\n");

// Free the
memoryfree(ptr);
printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated


printf("\nMemory successfully allocated using
calloc.\n");
#include
<stdio.h> // Free the
#include memory
<stdlib.h> free(ptr1);
printf("Calloc Memory successfully freed.\n");
int main() }
{
return 0;
// This pointer will hold the }
// base address of the block
createdint *ptr, *ptr1; Output:
int n, i; Enter number of elements: 5
Memory successfully allocated using
// Get the number of elements for the array malloc.Malloc Memory successfully
freed.
Memory successfully allocated using
calloc.Calloc Memory successfully
freed. // This pointer will hold the
// base address of the block
createdint* ptr;
C realloc() method int n, i;
“realloc” or “re-allocation” method in C is used to dynamically change
the memory allocation of a previously allocated memory. In other // Get the number of elements for the
words, if the memory previously allocated with the help of malloc or arrayn = 5;
calloc is insufficient,realloc can be used to dynamically re-allocate printf("Enter number of elements: %d\n", n);
memory.
Important:- // Dynamically allocate memory using
re-allocation of memory maintains the already present value and new calloc()ptr = (int*)calloc(n, sizeof(int));
blockswill be initialized with default garbage value.
Syntax: // Check if the memory has been successfully
ptr = realloc(ptr, newSize); // allocated by malloc or
notif (ptr == NULL) {
where ptr is reallocated with new size 'newSize'. printf("Memory not
allocated.\n");exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using
calloc.\n");

// Get the elements of the


arrayfor (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are:
");for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
If space is insufficient, allocation fails and returns a NULL }
pointer.#include <stdio.h> // Get the new size for the
#include <stdlib.h> arrayn = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
int main()
{
operations that can be performed on a file are:
1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
// Dynamically re-allocate memory using 2. Opening an existing file (fopen with attributes as “r” or “r+”)
realloc()ptr = realloc(ptr, n * sizeof(int)); 3. Reading from file (fscanf or fgets or fgetc)
4. Writing to a file (fprintf or fputs or fputc)
// Memory has been successfully allocated 5. Moving to a specific location in a file (fseek, rewind)
printf("Memory successfully re-allocated using realloc.\n"); 6. Closing a file (fclose)
The text in the brackets denotes the functions used for performing those
// Get the new elements of the operations.
arrayfor (i = 5; i < n; ++i) {
ptr[i] = i + 1; There are two kinds of files in a system. They are,
} 1. Text files (ASCII text 0-255 character set)
2. Binary files (image, vedio, audio)
// Print the elements of the array  Text files contain ASCII codes of digits, alphabetics and symbols.
printf("The elements of the array are:  Binary file contains collection of bytes (0’s and 1’s). Binary files are

");for (i = 0; i < n; ++i) { compiledversion of text files.


printf("%d, ", ptr[i]);
} MODE OF OPERATIONS PERFORMED ON A FILE IN C
LANGUAGE:
free(ptr); There are many modes in opening a file. Based on the mode of file, it can
} be opened for reading or writing or appending the texts. They are listed
below.
return 0;  r : Opens a file in read mode and sets pointer to the first character in the file.
It returns null if file does not exist.
}
 w : Opens a file in write mode. It returns null if file could not be opened. If file
Output: exists, data are overwritten. If not exist- new file will be created. and sets
Enter number of elements: 5 pointer to the last character in the file (if exist).
Memory successfully allocated using  a : Opens a file in append mode. It returns null if file couldn’t be opened.
Opens a file for read and write mode.
calloc.The elements of the array are: 1,
 r+ : Opens a file for read and write mode and sets pointer to the first
2, 3, 4, 5, character in the file.
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Basics of File Handling in C


So far the operations using C program are done on a prompt / terminal
which is not storedanywhere. But in the software industry, most of the
programs are written to store the information fetched from the program.
One such way is to store the fetched information in a file. Different
w+ : opens a file for read and write mode and sets pointer to the first

character in thefile.
Functions in File Operations:
 a+ : Opens a file for read and write mode and sets pointer to the first
character in thefile. But, it can’t modify existing contents.
Let us see the syntax for each of the above operations in a table:
File
operation Declaration & Description
Declaration: FILE *fopen (const char *filename, const char
*mode)
fopen() function is used to open a file to perform operations
such as reading, writing etc. In a C program, we declare a file
pointer and use fopen() as below. fopen() function creates a
new file if the mentioned file name does not exist.
FILE *fp;
fp=fopen (“filename”, ”mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the
fopen() – To file. Example: r, w, a, r+, w+ and a+. Please refer below the
open a file description for these mode of operations.

Declaration: int fclose(FILE *fp);


fclose() function closes the file that is being pointed by file
fclose() – To pointer fp. In a C program, we close a file as
close a file below. fclose (fp);

Declaration: char *fgets(char *string, int n, FILE *fp)


fgets function is used to read a file line by line. In a C program,
weuse fgets function as below.
fgets (buffer, size, fp);
where,
buffer – buffer to put the data in.
fgets() – To size – size of the buffer
read a file fp – file pointer
Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf() function
writes string into a file pointed by fp. In a C program, we
fprintf() – writestring into a file as below.
To write fprintf (fp, “some data”); or
into a file fprintf (fp, “text %d”, variable_name);
Opening or creating file
For opening a file, fopen function is used with the required access  Writing a file –:
modes. Some of thecommonly used file access modes are mentioned The file write operations can be perfomed by the functions fprintf
below. and fputs withsimilarities to read operations. The snippet for
File opening modes in C: writing to a file is as :
FILE *filePointer ;
 “r” – Searches file. If the file is opened successfully fopen( ) loads it into filePointer = fopen(“fileName.txt”, “w”);
memoryand sets up a pointer which points to the first character in it. If the fprintf(filePointer, "%s %s %s %d", "We", "are",
file cannot be opened fopen( ) returns NULL. "in", 2012);
 “w” – Searches file. If the file exists, its contents are overwritten. If the file  Closing a file –:
doesn’texist, a new file is created. Returns NULL, if unable to open file. After every successful fie operations, you must always close a file. For
 “a” – Searches file. If the file is opened successfully fopen( ) loads it into closing a file,you have to use fclose function. The snippet for closing a
memoryand sets up a pointer that points to the last character in it. If the
file is given as :
file doesn’t exist, anew file is created. Returns NULL, if unable to open file.
FILE *filePointer ;
 “r+” – Searches file. If is opened successfully fopen( ) loads it into memory
and setsup a pointer which points to the first character in it. Returns NULL, if filePointer= fopen(“fileName.txt”, “w”);
unable to openthe file. ---------- Some file Operations -------
 “w+” – Searches file. If the file exists, its contents are overwritten. If the file fclose(filePointer)
doesn’texist a new file is created. Returns NULL, if unable to open file.
 “a+” – Searches file. If the file is opened successfully fopen( ) loads it into
memory and sets up a pointer which points to the last character in it. If the Example 1: Program to Open a File, Write in it, And Close the File filter_none
file doesn’t exist, anew file is created. Returns NULL, if unable to open file.
// C program to Open a File, // Write in it, And Close the
As given above, if you want to perform operations on a binary file, then you File
have to append ‘b’ at the last. For example, instead of “w”, you have to use # include
“wb”, instead of “a+”you have to use “a+b”. For performing the operations <stdio.h> #
on the file, a special pointer called File pointer is used which is declared as include
FILE *filePointer; <string.h>
So, the file can be opened as
filePointer = fopen(“fileName.txt”, “w”) int main( )
The second parameter can be changed to contain all the attributes listed {
in the abovetable.
// Declare the file pointer
 Reading from a file – FILE *filePointer ;
The file read operations can be performed using functions fscanf or
fgets. Both thefunctions performed the same operations as that of // Get the data to be written
scanf and gets but with an additional parameter, the file pointer. So, it in filechar
depends on you if you want to read thefile line by line or character by dataToBeWritten[50]
character. = "GeeksforGeeks-A Computer Science Portal for Geeks";
And the code snippet for reading a file is as:
FILE * filePointer; // Open the existing file GfgTest.c using fopen()
filePointer = fopen(“fileName.txt”, “r”); // in write mode using "w"
fscanf(filePointer, "%s %s %s %d", str1, str2, str3, attribute filePointer =
fopen("GfgTest.c", "w") ;
&year);
// Check if this filePointer is null
else
// which maybe if the file does not {
existif ( filePointer == NULL )
{ printf("The file is now opened.\n") ;
printf( "GfgTest.c file failed to open." ) ;
}
// Write the dataToBeWritten into
the fileif ( strlen
( dataToBeWritten ) > 0 )
{

// writing in the file using


fputs() fputs(dataToBeWritten,
filePointer) ;fputs("\n",
filePointer) ;
}

// Closing the file using


fclose()fclose(filePointer) ;

printf("Data successfully written in file


GfgTest.txt\n");printf("The file is now closed.") ;
}
return 0;
}

Example 2: Program to Open a File, Read from it, And Close the File filter_none

// C program to Open a File, // Read from it, And Close


the File
# include
<stdio.h> #
include
<string.h>

int main( )
{

// Declare the file pointer


FILE *filePointer ;

// Declare the variable for the data to be read


from filechar dataToBeRead[50]; filePointer = fopen("GfgTest.c", "r") ;
// Check if this filePointer is null
// Open the existing file GfgTest.c using fopen() // which maybe if the file does not
// in read mode using "r" attribute existif ( filePointer == NULL )
{
printf( "GfgTest.c file failed to open." ) ;
}
else
{
printf("The file is now opened.\n") ;

// Read the dataToBeRead from the file


// using fgets() method
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
// Print the dataToBeRead
printf( "%s" ,
dataToBeRead ) ;
}

// Closing the file using


fclose()fclose(filePointer) ;
printf("Data successfully read from file
GfgTest.c\n");printf("The file is now closed.") ;
}
return 0;
}

INBUILT FUNCTIONS FOR FILE HANDLING IN C


LANGUAGE:
C programming language offers many inbuilt functions for handling files.
They are given below. Please click on each function name below to know
more details, example programs, output for the respective file handling
function.
FILE *file = fopen(“Hello.txt”, “a+”)
File
handling Descriptio
functions n
fopen () function creates a new file or
fopen () opensan existing file.

fclose () fclose () function closes an opened file.


getw () getw () function reads an integer from file. putw () putw () functions writes an integer to file.

fgetc () fgetc () function reads a character from file.

fputc () fputc () functions write a character to file.

/////////gets () gets () function reads line from keyboard.

//////////puts () puts () function writes line to o/p screen.

fgets () function reads string from a file,


fgets () oneline at a time.

fputs () fputs () function writes string to a file.

feof () feof () function finds end of file.

fgetchar () function reads a character from


fgetchar () keyboard.

fprintf () function writes formatted data to


fprintf () afile.

fscanf () function reads formatted data


fscanf () from afile.

fputchar () function writes a character


fputchar () ontothe output screen from keyboard input.

fseek () function moves file pointer


fseek () positionto given location.

SEEK_SET moves file pointer position to


SEEK_SET thebeginning of the file.

SEEK_CUR moves file pointer position to


SEEK_CUR given location.

SEEK_END moves file pointer position to


SEEK_END theend of file.

ftell () function gives current position of


ftell () filepointer.

rewind () rewind () function moves file pointer position


to the beginning of the file. 2. size of data to be written in the disk
3. number of such type of data
4. pointer to the file where you want to write.
getc () function reads character
getc () fromkeyboard.
fwrite(addressData, sizeData, numbersData, pointerToFile);
getch () function reads character
getch () fromkeyboard.
Example 3: Write to a binary file using fwrite()
getche () function reads character
getche () fromkeyboard and echoes to o/p screen. #include
<stdio.h>
getchar () function reads character #include
getchar () fromkeyboard. <stdlib.h>
putc () putc () function writes a character to screen. struct threeNum
{
putchar () function writes a character to
int n1, n2, n3;
putchar () screen.
};
printf () function writes formatted data to
printf () screen. int main()
{
sprinf () function writes formatted output int n;
sprinf () tostring. struct threeNum num;
FILE *fptr;
scanf () function reads formatted data
scanf () fromkeyboard. if ( (fptr = fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
sscanf () function Reads formatted input
sscanf () froma string.
// Program exits if the file pointer returns NULL.
exit(1); //to exit when file not exist
remove () remove () function deletes a file.
}
fflush () fflush () function flushes a file.
for(n = 1; n < 5; ++n)
{
num.n1 = n;
Reading and writing
fread fwrite
to a binary file num.n2 = 5*n;
an are used for reading from and writing to a file on the num.n3 = 5*n + 1;
Functio
d fwrite(&num, sizeof(struct threeNum), 1, fptr);
ns disk
}
respectively in case of binary files. fclose(fptr);
return

Writing to a binary file function. The functions take four


To write into a binary file, you need to fwrite
use thearguments:
1. address of data to be written in the disk
In this program, we create a newprogram.
file in the C drive.
#include
We declare a threeNu with three numbers - n1, n2 and n3, and define it in
structuremain the <stdio.h>
#include
function as num.
<stdlib.h>
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the nu and the second parameter takes the size of
struct threeNum
address ofthe structure {
threeNum. int n1, n2, n3;
Since we're only inserting one instance of num, the third parameter is 1. And, the };
last
parameter *fpt points to the file we're storing the data. int main()
Finally, we close the file. {
int n;
struct threeNum num;
Reading
freadfrom a binary file fwrite FILE *fptr;
Functio also take 4 arguments similar function as above.
n to the if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");

fread(addressData, sizeData, numbersData, pointerToFile); // Program exits if the file pointer returns NULL.
exit(1);
}
Example 4: Read from a binary file using fread()
the file.
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return
}

In this program, you read the program. and loop through the records one by
same fileone.
In simple terms, you read threeNu
one record threeNu size from the file pointed
nu of
by *fpt into the structure .
You'll get the same records you inserted in Example 3.

Getting data using fseek()


If you have many records inside a file and need to access a record at a
specific position,you need to loop through all the records before it to get
the record.
This will waste a lot of memory and operation time. An easier way to get to the
required
data can be achieved fseek .
usingAs the name fseek seeks the cursor to the given record in the file.
suggests,

Syntax of fseek()
fseek(FILE * stream, long int offset, int whence);
The first parameter stream is the pointer to the file. The second parameter is the
position
of the record to be found, and the third parameter specifies the location
where the offsetstarts.
Different whence in
fseek()
Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

SEEK_CUR Starts the offset from the current location of the cursor in
Example 5: fseek()
#include
<stdio.h>
#include Command Line Arguments in C
<stdlib.h>
The arguments passed from command line are called command line arguments. Thesearguments are
handled by main() function.
struct threeNum
{ To support command line argument, you need to change the structure of main()function as
int n1, n2, n3; given below.
};
1. int main(int argc, char *argv[] )
int main()
Here, argc counts the number of arguments. It counts the file name as the firstargument.
{
int n; The argv[] contains the total number of arguments. The first argument is the file namealways.
struct threeNum num;
FILE *fptr; Example
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ Let's see the example of command line arguments where we are passing one argumentwith file
printf("Error! opening file"); name.

// Program exits if the file pointer returns NULL. 1. #include <stdio.h>


exit(1); 2. void main(int argc, char *argv[] ) {3.
}
4. printf("Program name is: %s\n", argv[0]);5.

// Moves the cursor to the end of the file 6. if(argc < 2){
fseek(fptr, -sizeof(struct threeNum), SEEK_END); 7. printf("No argument passed through command line.\n");8. }
9. else{
for(n = 1; n < 5; ++n) 10. printf("First argument is: %s\n", argv[1]);
{
11. }
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3); 12.}
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
Run this program as follows in Linux:
}
fclose(fptr);
1. ./program hello

return 0;
}
This program will start reading the records
from the file(last to first) and prints it.
Run this program as follows in Windows from command line:

1. program.exe hello

Output:

Program name is: programFirst


argument is: hello

If you pass many arguments, it will print only one.

1. ./program hello c how r u

Output: It is difficult to display an image of any size on the computer screen. This method issimplified
by using Computer graphics. Graphics on the computer are produced by using various
algorithms and techniques. This tutorial describes how a rich visual experience is provided to
Program name is: programFirst the user by explaining how all these processed by the computer.
argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as asingle
argument only.
Introduction of Computer Graphics
Computer Graphics involves technology to access. The Process transforms and presentsinformation in
1. ./program "hello c how r u" a visual form. The role of computer graphics insensible. In today life, computer graphics has now
become a common element in user interfaces, T.V. commercial motion pictures.
Output:
Computer Graphics is the creation of pictures with the help of a computer. The end product of the
Program name is: program computer graphics is a picture it may be a business graph, drawing, andengineering.
First argument is: hello c how r u
In computer graphics, two or three-dimensional pictures can be created that are used for research.
Many hardware devices algorithm has been developing for improving thespeed of picture generation
with the passes of time. It includes the creation storage of models and image of objects. These
models for various fields like engineering, mathematical and so on.
You can write your program to print all the arguments. In this program, we are printingonly argv[1],
that is why it is printing only one argument.
Today computer graphics is entirely different from the earlier one. It is not possible. It is an
interactive user can control the structure of an object of various input devices.
int main(int argc, char *argv[])
{
/* the first command-line parameter is in
argv[1](arg[0] is the name of the program) */
FILE *fp = fopen(argv[1], "r"); /* "r" = open for reading */

Computer Graphics
Graphics: Introduction, Constant, Data types and global variables used in graphics,
Libraryfunctions used in drawing, Drawing and filling images, GUI interaction within the
program.
line(x1, y1, x2, y2);getch();
Definition of Computer Graphics: closegraph();

}
Graphics programming in C used to drawing various geometrical
shapes(rectangle, circle eclipse etc), use of mathematical function in
drawing curves, coloring an objectwith different colors and patterns and 2. Explanation of Code :
simple animation programs like jumping ball and moving cars.
The first step in any graphics program is to include graphics.hheader file.
The graphics.hheader file provides access to a simple graphics library that
makes itpossible to draw lines, rectangles, ovals, arcs, polygons, images, and
Graphics (graphics.h) - C Programming strings on a graphical window.

The second step is initialize the graphics drivers on the


computerusing initgraphmethod of graphics.hlibrary.
Graphics programming in C used to drawing various geometrical
shapes(rectangle, circle eclipse etc), use of mathematical function in
drawing curves, coloring an objectwith different colors and patterns and void initgraph(int *graphicsDriver, int *graphicsMode, char

simple animation programs like jumping ball and moving cars. *driverDirectoryPath);

1. First graphics program (Draw a line) It initializes the graphics system by loading the passed graphics driver then
changingthe system into graphics mode. It also resets or initializes all
#include<graphics.h> graphics settings like color, palette, current position etc, to their default
#include<stdio.h> values. Below is the description ofinput parameters of initgraph function.
#include<conio.h>
 graphicsDriver : It is a pointer to an integer specifying the
graphics driverto be used. It tells the compiler that what graphics
void main(void) { driver to use or to automatically detect the drive. In all our
int gdriver = DETECT, gmode;int x1 = programs we will
200, y1 = 200; use DETECTmacro of graphics.h library that instruct compiler for
autodetection of graphics driver.
int x2 = 300, y2 = 300;
 graphicsMode : It is a pointer to an integer that specifies the
clrscr(); graphicsmode to be used. If *gdriveris set to DETECT,
then initgraphsets *gmodeto the highest resolution available for the
initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi"); detected driver.
 driverDirectoryPath : It specifies the directory path where
graphics driverfiles (BGI files) are located. If directory path is not
provided, then it will search for driver files in current working
directory directory In all our sample graphics programs you have
We have declared variables so that we can keep track of starting and ending point.
CYAN 3 Yes Yes
int x1=200, y1=200;int

x2=300, y2=300;
RED 4 Yes Yes
No, We need to pass just 4 parameters to the linefunction.
MAGENTA 5 Yes Yes
line(x1,y1,x2,y2);

BROWN 6 Yes Yes


lineFunction Draws Line From (x1,y1) to (x2,y2) .
LIGHTGRAY 7 Yes Yes
Syntax : line(x1,y1,x2,y2);

Parameter Explanation DARKGRAY 8 NO Yes

 x1 - X Co-ordinate of First Point LIGHTBLUE 9 NO Yes


 y1 - Y Co-ordinate of First Point
LIGHTGREEN 10 NO Yes
 x2 - X Co-ordinate of Second Point
 y2 - Y Co-ordinate of Second Point LIGHTCYAN 11 NO Yes

At the end of our graphics program, we have to unloads the graphics drivers
and sets LIGHTRED 12 NO Yes
the screen back to text mode by calling closegraphfunction.
LIGHTMAGENTA 13 NO Yes
3. Colors in C Graphics Programming
YELLOW 14 NO Yes

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 WHITE 15 NO Yes
color of text, to color a closed shape etc (Foreground and Background
Color). To specify a color, we can either use color constants like BLINK 128 NO *
setcolor(RED), or their corresponding integer codes likesetcolor(4). Below

CONSTANT VALUE BACKGROUND? FOREGROUND?


***** To display blinking characters in text mode, add BLINK to the
foregroundcolor. (Defined in conio.h)
BLACK 0 Yes Yes
4. Graphics example using color
BLUE 1 Yes Yes
//Include the graphics header file

#include<graphics.h> #include<stdio.h>
GREEN 2 Yes Yes
#include<conio.h>

void main()

//Initialize the variables for the graphics driver and modeint 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 rectanglefunction

rectangle(50,50,100,100);

getch();

//unloads the graphics drivers

closegraph();
}

You might also like