C Program to Draw Stars in Night Sky Using C Graphics

Write a program in C to draw stars in night sky using graphics.h header file

In this program, we will randomly select 500 pixels on screen and color them in while. We will use putpixel functions of graphics.h header file to color a pixel at (x, y).

C program to draw stars in night sky using graphics

In this program, we first initialize graphics mode, by passing graphics driver(DETECT), default graphics mode and specifies the directory path where initgraph looks for graphics drivers (*.BGI). Then we will randomly select any (x, y) coordinate using rand, getmaxx and getmaxy function and color it using putpixel function. After 500 milliseconds we will clear screen and again paint the screen with stars until presses any key.

C Program to Draw Stars in Night Sky Using C Graphics

#include <conio.h>
#include <graphics.h>
#include <dos.h>
#include <stdlib.h>
 
int main() {
    int gd = DETECT, gm;
    int i, x, y;
    initgraph(&gd, &gm, "C:\\TC\\BGI");
        
 
 while (!kbhit()) {
      /* color 500 random pixels on screen */
   for(i=0; i<=500; i++) {
       x=rand()%getmaxx();
          y=rand()%getmaxy();
          putpixel(x,y,15);
      }
      delay(500);
 
      /* clears screen */
      cleardevice();
    }
 
    getch();
    closegraph();
    return 0;
}

Program Output
Here is the screen shot of twinkling night sky animation.

STARS