Objective:
Turtle Graphics is a popular way to introduce programming to beginners. In this approach, a ‘turtle’ is moved around the screen to create shapes and patterns. The turtle can be controlled using commands like forward, backward, turn, etc. This program demonstrates the use of Turtle Graphics in C, which can be used to draw simple geometric shapes and patterns.
Code:
#include #include #include void drawShapes() { int gd = DETECT, gm; initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Drawing a Square for (int i = 0; i < 4; i++) { forward(100); right(90); } // Moving to new position penup(); forward(150); pendown(); // Drawing a Triangle for (int i = 0; i < 3; i++) { forward(100); right(120); } // Moving to new position penup(); forward(150); pendown(); // Drawing a Circle circle(50); getch(); closegraph(); } int main() { drawShapes(); return 0; }
Explanation of the Program Structure:
The program uses the C language to create graphical shapes using the graphics.h
library. Below is a breakdown of the code:
- Libraries Included:
#include <graphics.h>
: This library is required to use the graphics functions for drawing.#include <conio.h>
: This library provides console input/output functions (likegetch()
).
- Initializing Graphics Mode: The
initgraph()
function initializes the graphics mode. - Drawing Shapes:
- The
forward()
function moves the turtle forward by a specified distance. - The
right()
function turns the turtle to the right by a specified angle. - Shapes such as a square, triangle, and circle are drawn by repeating the
forward()
andright()
functions in different patterns.
- The
- Graphics Closing: After drawing the shapes, the
getch()
function is used to wait for user input, andclosegraph()
is called to close the graphics window.
How to Run the Program:
To run this C program using Turtle Graphics, follow these steps:
- Install a C compiler that supports graphics, such as Turbo C++ or any other compatible IDE that supports
graphics.h
. - Ensure that you have the correct path to the BGI directory for
graphics.h
. - Compile the program in your IDE and run it. The graphics window will open, displaying the shapes.