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 ??
15 Antworten
+ 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
+ 2
Calvin Thomas you mean to declare I and j variable while intialising the loops?
+ 2
I used to declare inside the loop but declaring it in main function is better because it will initially allocate memory for it
+ 2
Calvin Thomas You will not notice it here. But the one of main function have less time complexity
+ 2
My pleasure
+ 1
Atul I see, thanks.
+ 1
Calvin Thomas but there are certain instances when you have to initilize in the loop only
+ 1
Like in patterns
https://code.sololearn.com/ccB8VJzFBNO6/?ref=app
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;
}
0
Enter the number:4
Enter th elements in an array:2 5 7 4
Second largest Element:7
Smallest Element:2
Process finished.
0
This error : second largest element :7 but second largest element is 5
0
Thank You.
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?
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?
0
Atul So is it faster?