hello I been working on a swap program and this is about my third one trying to get it working now I'm having a problem i keep getting 0's added into it right now the output is 4, 0 , 5, 0 ,16.
Could anyone tell me where the 0's are coming from or how to fix this thanks for any advise.

#include <iostream>
using namespace std; 
int main (int argc, char * const argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
	int line [5] = { 4, 5, 32, 40, 16 };
	int x = 0; // count
	int temp = 0;
	int r = 0;


	while(x<4){
	if (r > 5){
	r = 0;
	x++;
	}
	
	int a = line[0+r];
	int b = line[1+r];
	
	if (a > b ){
//		temp = line[r];
//		line[r] = line[r+1];
//		line[r+1] = temp;
	temp = a;
	a = b;
	b = temp;
	line[0+r] = a;
	line[1+r] = b;
	
	}
	r++;
	}
for (int i = 0; i < 5; i++)
		cout << line[i] << " ";

    return 0;
}

Recommended Answers

All 2 Replies

You're allowing the r value to get to 6 before you reset it. When it reaches 4 you already have problems because you access line[r+1], i.e. line[5], which doesn't exist.
Try resetting when r > 3.

That fixed it thanks

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.