Unit–5 problem solving c
Unit–5 problem solving c
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.
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.
// Free the
memoryfree(ptr);
printf("Malloc Memory successfully freed.\n");
Example 2: Program to Open a File, Read from it, And Close the File filter_none
int main( )
{
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.
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_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.
// 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:
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.
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);
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
#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();
setcolor(BLUE);
rectangle(50,50,100,100);
getch();
closegraph();
}