i have a problem

ok, so my program is a array size 16 and i filled the array with A-P to output it forward using a for loop, it works. but when i try to output the array in reverse with my second for loop it only outputs B-Q in reverse(QPONMLKJIHGFEDCB), when i need it to output A-P in reverse. it seems that the reverse for loop is ending at 'B' rather then 'A' and starting with 'Q'. i cant figure out how to fix it, and i tried for an hour, please help!

the program is:

#include<iostream>

using namespace std;

int main()

{
const int size=16;
char myarr[size];
int ctr;
char mychr= 'A';

cout << "\nthe forward array is:\n\n"<< myarr[mychr];

for(ctr=0;ctr<16;ctr++)
{
cout<< mychr;

mychr++;
}


cout <<"\n\n\n";


cout << "the array in reverse is:"<< "\n\n"<< myarr[mychr];

for ( ctr=15;ctr>=0;ctr--)
{
cout << mychr;

mychr--;

}



cout <<"\n\n\n";
system("pause");
return 0;
}
On the last loop of the first for loop, you increment mychr one more time beyond what was printed. So when you start the second loop, it's starting at Q.

You're not actually using the array here. You're just printing out the incremented value of the char variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main()
{
	int ctr;
	char mychr= 'A';

	cout << "\nthe forward array is: ";

	for(ctr=0;ctr<16;ctr++)
	{
		cout<< mychr;
		mychr++;
	}

	cout << endl;
	mychr--; // decrement the mychr variable
	
	cout << "the array in reverse is: ";

	for (ctr=15;ctr>=0;ctr--)
	{
		cout << mychr;
		mychr--;
	}
	
	return 0;
}


the forward array is: ABCDEFGHIJKLMNOP
the array in reverse is: PONMLKJIHGFEDCBA
Last edited on
Topic archived. No new replies allowed.