sup guys
im trying to implement a nested for loop for a 2 dimension array that initializes the array to the character '*'. but its just printing out garbage, i think im messing up on my syntax :sad:.....some help would be appreciated

here is what i got so for:

char initialize[12][5];
int row;
int col;

for(row=0;row<13;row++)
{for(col=0;col<6;col++)
initialize[row][col]='*';
cout<<initialize[row][col]<<endl;}

Recommended Answers

All 4 Replies

Greetings,

This can be fixed quite easily. Array subscripts always start at zero in C, so elements are initialize[0], initialize[1], ..., initialize[11]. Meaning, you cannot write to the array index of 12, since it does not exist. To break it down, take the number 12. Start at 0 and count up 12 times, you come up with 11. Your program crashes because you are trying to write out-of-bounds to the array. You can simply fix it by changing the number within your for loop:

for(row=0;row<12;row++)
	for(col=0;col<5;col++)

The reason this works is because you are starting at 0, and looping to 11. The last number before 12 is 11, and since we did < 12 instead of <= 12 your loop will stop at 11. That applies to row of course, and the same concept with column.

Hope this helps,
- Stack Overflow

ty stack...i changed the values like u suggested...but im still unable to get the desired results. it should be looking like:

* * * * * *
* * * * * *
etc........but it still gives me a single column of junk......i get the feelin my parenthesis might be wrong....and i've tried changin them to see if my results change but it just does'nt work

Ah, Simple.

We would have to break this up into different pieces of code. The first piece would be:

for(row=0;row<12;row++)
	for(col=0;col<6;col++)
		initialize[row][col]='*';

The reason we don't print here is because we are going to need a different way and concept to print all 6 columns, but only 2 rows of each. That's why we are going to take another approach. Firstly, lets create another integer called i. Now, lets make a loop out of it. We will start at 0, and loop until 1; or in this case < 2. Inside this loop we will call on our column loop to loop through all 6 characters, print it and add a space at the end. Each time our first loop passes, we will add a new line. If this makes sense, then this should too:

// Two rows
for(i=0;i<2;i++) {
	// Six columns
	for(col=0;col<6;col++)
		cout << initialize[i][col] << " ";
	// Six columns are over; time for new line
	cout << endl;
}

We add this after our initialization. Hope this helps, and makes sense.

If you have further questions, please feel free to ask.


- Stack Overflow

ty stack...it works

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.