Turtle Graphics is a popular way to introduce programming concepts to beginners. It provides an easy and interactive way to create drawings and patterns using a “turtle” which moves on the screen. In this guide, we’ll use C++ to implement turtle graphics. While the turtle module is native to Python, we can simulate similar behavior in C++ by using libraries like the graphics.h library in certain environments, or using other graphical libraries such as SFML, SDL, or OpenGL.
Objective
The objective of this program is to use Turtle Graphics principles to draw simple shapes such as squares, circles, and other patterns. This will help beginners understand the power of graphics in C++ and how to control graphical objects (like the turtle) on the screen.
C++ Code for Turtle Graphics Program
#include
#include
#include
using namespace std;
void drawSquare(int x, int y, int size) {
for (int i = 0; i < 4; i++) {
// Move the turtle forward by 'size' units
forward(size);
// Turn the turtle 90 degrees to the right
right(90);
}
}
void drawCircle(int x, int y, int radius) {
// Draw a circle with given radius
circle(x, y, radius);
}
int main() {
// Initialize graphics window
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Drawing a square at coordinates (200, 200) with side length 100
drawSquare(200, 200, 100);
// Draw a circle at (300, 300) with radius 50
drawCircle(300, 300, 50);
// Wait for user input before closing
getch();
// Close the graphics window
closegraph();
return 0;
}
Program Explanation
The program starts by initializing the graphics library and setting up the graphical window where shapes will be drawn. The main function calls the drawing functions for a square and a circle.
- #include : This header file provides the necessary functions for graphical operations in C++.
- initgraph(&gd, &gm, “”): Initializes the graphics mode and prepares the graphics window for drawing. ‘gd’ and ‘gm’ are variables that hold the graphics driver and mode.
- drawSquare: This function takes the starting coordinates (x, y) and a size, then draws a square by moving the turtle forward and turning it 90 degrees four times.
- drawCircle: This function draws a circle with a given radius at a specified position.
- getch: Waits for the user to press a key before closing the graphics window.
- closegraph: Closes the graphics window and ends the program.
How to Run the Program
To run this program:
- Install a C++ development environment that supports the graphics.h library (e.g., Turbo C++ or Dev-C++).
- Copy the above code into a new file with a .cpp extension.
- Compile and run the program in the C++ environment.
- After running, you will see a square and a circle drawn in the graphical window.