0

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;
}
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by acoxia
0

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.

This question has already been answered. 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.