I am working with a small group to put together a project and my part involves making a single character move thru a 2d array. Here is the code so far:
#include<iostream>
using namespace std;
void printarray(int);
int main()
{
int num;
cout<<"enter a number\n";
cin>>num;
printarray(num);
system("pause");
return 0;
}
void printarray(int n)
{
char array[n][n];
for(int x=0, i=1; x<n; x++, i++)
{
for(int y=0; y<n; y++)
{
//array[x][y]=i;
array[x][y]=' '; //assigning space ' ' to all elements of matrix
}
}
for(int y=0; y<n; y++)
{
for(int x=0; x<n; x++)
{
cout<<"|__"<<array[x][y]<<"__| ";
}
cout<<endl<<endl<<endl;
}
}
The end result is a square grid that is setup thru user inputs.
What I wanted to happen next was have array[0][0] initialized to an "x" character and have it move sequentially thru the grid. I keep having problems when I just try to put the X in the first box. Can someone help me with this?
What is the specific trouble? If you can assign array[x][y]=' '; with no problems then array[0][0]='x'; ought to work as well. Use of double quotes (") here may cause a problem though.
Your code shouldn't be working at all because static variable sized arrays:
1 2 3
void printarray(int n)
{
char array[n][n];
are supposedly forbidden. It seems that some compilers permit this though.
I apologize for taking so long to reply fun2code, this week kept me away from the computer. Well I changed the printarray(int n) to printarray(char n) an suddenly I could assign characters to specific areas of my array as I wanted to:
void printarray(char n)
{
char array[n][n];
for(int x=0, i=1; x<n; x++, i++)
{
for(int y=0; y<n; y++)
{
array[x][y]=' '; //assigning space ' ' to all elements of matrix
}
array[0][0] ='x';
array[0][n-1] ='x';
array[n-1][0] ='x';
array[n-1][n-1] ='x'; This allows me to put characters at the four corners of a 2D array which is the first part of the project that I wanted to accomplish. Thank you.
What I was looking to do now was have a second character move across the 2D array one space at a time every couple of seconds. Can I have some help to start this function?
Glad that was helpful.
Sorry, I don't know how to perform an animation in a console program. I hear it can be done though. I see boost mentioned frequently.
For me, console programs are only for problems which involve taking user input through a series of prompts then doing some calculations and printing the result.