Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program that draws 2 white circles somewhere in a dark gray rectangu

ID: 3794687 • Letter: W

Question

Write a C++ program that draws 2 white circles somewhere in a dark gray rectangular (not square) PGM. You may hard-code the row and column locations, radius and brightness levels for the two circles, or make it a little more challenging and prompt the user for the circle information.

For this, it may be helpful to use the sqrt( ) function, which returns the square root of a number. For example:

y = sqrt(2.0);

sets y to ~1.414. If the distance of a pixel from the center of the circle is less than the radius, you're inside the circle. Otherwise you're outside.

Outside the circle, assign the each pixel a random number between 0 & 64. (See the rand(...) function in chapter 3. The modulus operator will come in handy to truncate your random numbers to a value between 0 and 255.

For more excitement (this IS exciting, isn't it?) you could shade the the circles as you get closer to the center, or shade the random numbers outside the circle. Here's a circle example, with shading towards the center of the circle. (This is from a previous semester, where the challenge was to draw a single black circle on a random background, centered in the image):

circle.pam 640 x 480 pm ecits gray (B94KB) 100% Or, with a little shading to make it more interesting: circle shading.pgm

Explanation / Answer

The problem is to draw a circle inside rectangular image.

The problem can be broken as

Code

#include <cstdlib>

#include <fstream>

#include <iostream>

#include <string>

#include <math.h>

using namespace std;

int main(int argc, char *argv[])

{

//name of the output file

   string filename = "test.pgm";

   // image dimensions

   unsigned short width = 480;

   unsigned short height = 640;

   // radius of the circle

   double radius = 192;

   //center of the circle

   double xc = height / 2.0;

   double yc = width / 2.0;

   ofstream fout(filename);

   int r, c, val;

   //write the headers of pgm file

   fout << "P5 " << width << " " << height << " 255 ";

   //draw image

   for (r = 0; r < height; r++)

       for (c = 0; c < width; c++) {

           double a = xc - r;

           double b = yc - c;

           double d = sqrt(a * a + b * b);

           if (d > radius) {

               //if point lies outside the circle set pixel to random value between 0 64

               val = (int) rand() % 64;

           } else {

               //if point lies inside circle set it to 255(white pixel)

               val = (int) 255;

           }

           fout << (char) (val);

       }

   fout.close();

   return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote