Here is another C program to draw a Square or Triangle shape based on the user’s choice. This program will ask the user whether he wants to draw a Square or a Rectable and based on the option he selected, the program would print the pattern.
C Program:
#include <stdio.h>
void drawSquare(int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("* ");
}
printf("\n");
}
}
void drawTriangle(int size) {
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
}
int main() {
int choice, size;
printf("Choose the shape to draw:\n");
printf("1. Square\n");
printf("2. Triangle\n");
scanf("%d", &choice);
printf("Enter the size of the shape: ");
scanf("%d", &size);
switch (choice) {
case 1:
drawSquare(size);
break;
case 2:
drawTriangle(size);
break;
default:
printf("Invalid choice!\n");
break;
}
return 0;
}
Based on user choice, The program calls the drawSquare or the drawTriangle function and then it draws the shapes using ASCII characters.
This program can be used in schools /colleges. Hope this helped you.