1

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?

2
Contributors
2
Replies
3
Views
13 Years
Discussion Span
Last Post by yeohsli
1
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])

Edited by Dani: Formatting fixed

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.