I'm having trouble trying to figure out how to create a Cartesian Graph for the formula y=x^2 so that it looks like the following.

------*


---*


--*


-*
*

*please disregard the -*

Current grid parameters:
20 X 20 array with step 1

I know I have to create a char[20][20] array and then somehow get a function to return x*x but I really cant picture it in my head on how to do this. Any help would be appreciated, because I'm lost.

Calculate different values of y by incrementing x by small steps.

In the char array set the value char[x][y] to '*'

For example
y=0 if x=0 i.e char[0][0] = '*'
y=1 if x=1 i.e char[1][1]='*'
y=4 if x=2 i.e char[2][4]='*'

and so on. Though it will go out of bounds for x=5. The larger the array the better.

After that you need to display the matrix in such a manner that the left most point correspondes to char[0][0], x increments right horizontally. And y incrementes top vertically.

I suggest you to use graphics if possible.

Ok I was able to get this to work using the following code.

#include <iostream>
using namespace std;

float f(int x);

int main() {

int xdim = 20;
int ydim = 70;  
char a[xdim][ydim];
float step = 1;
float k;

for ( int i = 0 ; i < xdim ; i++ )
    for ( int j = 0 ; j < ydim ; j++ ){  
        k = step * i;
        if ( k == f(j))
           a[i][j] = '*';
           else
           a[i][j] = ' ';
        }
        
for ( int i = 0 ; i < xdim ; i++ ){
    for ( int j = 0 ; j < ydim ; j++ ){ 
        cout << a[(xdim -1) - i][j];
        }  
    cout << endl;
}      
    
  cout << endl;
  system ("pause");
  return 0;
} 

float f(int x) { 
    return x*x; 
  }

What I'm tring to figure out now is how to get the step size to work propery. This is what I'm looking for

The step value is an increment. It is the amount by which you must change the x
value. So if step is 1, then you are plotting x^2 at points
0 1 2 3 4 5 ...

If step is 1/2, then you are plotting x^2 at points

0 1/2 1 1.5 2 2.5 3 3.5 ...

If step was, say 0.01, then you are plotting x^2 at points

0 0.01 0.02 0.03 0.04 ...

What I can't figure out is how to get the step working properly. Any help is appreciated.

This article has been dead for over six months. Start a new discussion instead.