problem with array

this code get 5 numbers and find bigger number
it works correctly but when i insert 5th number,it doesnt work correctly,it just compared entered numbers:1,2,3,4

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
27
28
29
30
31
32
33
34

#include <iostream>
using namespace std;
int main(){
	
	int num[5],com,temp;
	
	for(int i=0;i<5;i++){
		
		cout<<"enter number: ";
		cin>>num[i];
	}
	
	for(int i=0;i<5;i++){
		
		for(int j=0;j<i;j++){
			
			if(num[j]>num[j+1]){
				
				temp=num[j];
				num[j]=num[j+1];
				num[j+1]=temp;
			
			}
			com=temp>num[j]?temp:num[j];	
		}	
	}
		
	cout<<com;
	
	return 0;
}

i've changed to this and it works very well
in line 25 i added 1 to num[j] like this num[j+1]
can you tell me why j+1?
i just added 1 to j
i dont know reason
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
27
28
29
30
31
32
#include <iostream>
using namespace std;
int main(){
	
	int num[5],com,temp;
	
	for(int i=0;i<5;i++){
		
		cout<<"enter number: ";
		cin>>num[i];
	}
	
	for(int i=0;i<5;i++){
		
		for(int j=0;j<i;j++){
			
			if(num[j]>num[j+1]){
				
				temp=num[j];
				num[j]=num[j+1];
				num[j+1]=temp;
			
			}
			com=temp>num[j]?temp:num[j+1];	
		}	
	}
		
	cout<<com;
	
	return 0;
}
Last edited on
Easier and faster way to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<algorithm> //sort function library

int arr[5];
for (int i = 0;  i<5;  i++){
cin>>arr[i];
}

sort(arr, arr+5); //sorts array arr from smaller to bigger

cout<<arr[4]; //outputs final element, biggest since the array was sorted

return 0;
}
Last edited on
Topic archived. No new replies allowed.