i m just learning pointer in c++. and i coded a program. however the output is not wat i wanted. :?:

#include <iostream>
using namespace std;

void descending( int *, const int );
void ascending( int *, const int );

int main()
{
	int input[10];
	int *p = input;

	for (int i=0; i<=7; i++)
	{
		cout << "Enter an integer: ";
		cin >> p[i];
	}
	descending(p, 8);
	ascending(p, 8);

	return 0;
}

void descending( int *a, const int )
{
	int temp;
	for (int pass=1; pass<=7; pass++)
	{
		for (int k=0; k<=7; k++)
			if (a[k] < a[k+1])
			{
				temp = a[k];
				a[k] = a[k+1];
				a[k+1] = temp;
			}
	}
	
	cout << "\nDescending order:" << endl;
	for (int i=0; i<8; i++)
	{
		cout << a[i] << " ";
	}

	cout << endl;
}

void ascending( int *a, const int )
{
	int temp;
	for (int pass=1; pass<=7; pass++)
	{
		for (int k=0; k<=7; k++)
			if (a[k] > a[k+1])
			{
				temp = a[k];
				a[k] = a[k+1];
				a[k+1] = temp;
			}
	}
	
	cout << "\nAscending order:" << endl;
	for (int i=0; i<8; i++)
	{
		cout << a[i] << " ";
	}

	cout << endl;

}

can someone tell me what's wrong with this code?

Recommended Answers

All 2 Replies

for (int k=0; k<=7; k++)
if (a[k] > a[k+1])

You're going off the end of the array.

for (int k=0; k<7; k++)
if (a[k] > a[k+1])

thanks for the help

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.