0

/*Second largest and Smallest Number in an one dimensional array of size 15 elements*/ #include <stdio.h> //Compiler version

Help me friends because output become incorrect .why ??

15th May 2021, 6:31 PM
Vrushabh
Vrushabh - avatar
15 Respuestas
+ 1
#include <stdio.h> //Compiler version gcc 6.3.0 //Now we define main function int main() { int n, temp,arr[15],i,j; printf("Enter the number:"); scanf("%d",&n); printf("Enter th elements in an array:"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n;i++){ for(j=i+1;j<n;j++) { if(arr[i]>arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } }} printf("\nSecond largest Element:%d",arr[n-2]); printf("\nSmallest Element:%d",arr[0]); return 0; } // Check if this works
15th May 2021, 8:17 PM
Atul [Inactive]
+ 2
Calvin Thomas you mean to declare I and j variable while intialising the loops?
16th May 2021, 5:50 AM
Atul [Inactive]
+ 2
I used to declare inside the loop but declaring it in main function is better because it will initially allocate memory for it
16th May 2021, 6:13 AM
Atul [Inactive]
+ 2
Calvin Thomas You will not notice it here. But the one of main function have less time complexity
16th May 2021, 6:25 AM
Atul [Inactive]
+ 2
My pleasure
16th May 2021, 7:01 AM
Atul [Inactive]
+ 1
Atul I see, thanks.
16th May 2021, 6:48 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Calvin Thomas but there are certain instances when you have to initilize in the loop only
16th May 2021, 7:58 AM
Atul [Inactive]
16th May 2021, 8:01 AM
Atul [Inactive]
0
/*Second largest and Smallest Number in an one dimensional array of size 15 elements*/ #include <stdio.h> //Compiler version gcc 6.3.0 //Now we define main function int main() { int n, temp,arr[15],i,j; printf("Enter the number:"); scanf("%d",&n); printf("Enter th elements in an array:"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(j=i+1;j<n;j++) { if(arr[i]>arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } printf("\nSecond largest Element:%d",arr[n-2]); printf("\nSmallest Element:%d",arr[0]); return 0; }
15th May 2021, 6:32 PM
Vrushabh
Vrushabh - avatar
0
Enter the number:4 Enter th elements in an array:2 5 7 4 Second largest Element:7 Smallest Element:2 Process finished.
15th May 2021, 6:33 PM
Vrushabh
Vrushabh - avatar
0
This error : second largest element :7 but second largest element is 5
15th May 2021, 6:34 PM
Vrushabh
Vrushabh - avatar
0
Thank You.
16th May 2021, 1:44 AM
Vrushabh
Vrushabh - avatar
0
Atul Is there anu advantage in initializing the variables 'i' and 'j' in the main function's scope rather than in the for-loop's scope each time?
16th May 2021, 5:44 AM
Calvin Thomas
Calvin Thomas - avatar
0
Atul Which, in your opinion, is the better choice, declaring the variable inside the for loop or inside the main function, considering that you have many for loops?
16th May 2021, 6:01 AM
Calvin Thomas
Calvin Thomas - avatar
0
Atul So is it faster?
16th May 2021, 6:17 AM
Calvin Thomas
Calvin Thomas - avatar