Practical No:08 - Write a C program for 2D
Rotation.
int main() {
int gd = DETECT, gm;
2. Perform a counterclockwise 45° rotation of
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
triangle A(2,3) B(5,5) C(4,4) about point(1,1)
#include <stdio.h>
int cx = 150, cy = 80; // Center of rotation,
#include <graphics.h>
even closer to the text
#include <math.h>
float angle = 45.0; // Rotation angle
#include <conio.h>
// Original triangle vertices (further
#define PI 3.14159265 adjusted closer to text)
int x1 = 100 + cx, y1 = 50 + cy;
void rotatePoint(int *x, int *y, int cx, int cy, int x2 = 200 + cx, y2 = 50 + cy;
float angle) {
int x3 = 150 + cx, y3 = 150 + cy;
float rad = angle * PI / 180.0;
float cosA = cos(rad);
// Rotate points
float sinA = sin(rad);
int x1_rot = x1, y1_rot = y1;
int x2_rot = x2, y2_rot = y2;
int tempX = *x - cx;
int x3_rot = x3, y3_rot = y3;
int tempY = *y - cy;
rotatePoint(&x1_rot, &y1_rot, cx, cy, angle);
*x = cx + (int)(tempX * cosA - tempY * sinA);
rotatePoint(&x2_rot, &y2_rot, cx, cy, angle);
*y = cy + (int)(tempX * sinA + tempY *
rotatePoint(&x3_rot, &y3_rot, cx, cy, angle);
cosA);
}
// Draw original triangle in red
setcolor(RED);
void drawTriangle(int x1, int y1, int x2, int y2,
int x3, int y3, int color) { drawTriangle(x1, y1, x2, y2, x3, y3, RED);
setcolor(color);
line(x1, y1, x2, y2); // Draw rotated triangle in green
line(x2, y2, x3, y3); setcolor(GREEN);
line(x3, y3, x1, y1); drawTriangle(x1_rot, y1_rot, x2_rot, y2_rot,
x3_rot, y3_rot, GREEN);
}
// Display name and roll number text at the
top
setcolor(WHITE);
outtextxy(10, 10, "NAME: KASHIF ANSARI
ROLLNO: 230404");
getch(); // Wait for user input
closegraph(); // Close graphics mode
return 0;