this c program not running properly | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

this c program not running properly

I made a program to determine second largest element in an array:- #include<stdio.h> #include<conio.h> int main() { int a[10],i,j,l=0,b; for(i=0;i<10;i++) { scanf("%d",&a[i]); } for(i=0;i<10;i++) { for(j=0;j<10;j++) { if(a[i]<a[j]&&a[j]!=b) { l++; b=a[i]; } } if(l==1) { printf("Second largest = %d",a[i]); break; } } return 0; } but it is not printing anything. why? pls help.

17th Sep 2017, 5:56 AM
Shantanu Shinde
Shantanu Shinde - avatar
10 Answers
+ 13
Are you trying to run this using Code Playground?
17th Sep 2017, 6:38 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
//Try this. //Just FYI, C++ is backwards compatible with C, but loops and input does not work well on Code Playground. scanf() is also not recognised. // This works, but you have to modify it to take user input. #include<stdio.h> int main() { int a[10] = {1,2,4,3,9,8,0,5,6,7}; for (int i = 0; i < 10; i++) for (int j = 0; j < 10 - 1 - i; j++) if (a[j] < a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } printf("Second largest = %d",a[1]); return 0; }
17th Sep 2017, 7:21 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
For one, b was never initialized.
17th Sep 2017, 7:23 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
it will work in c++
17th Sep 2017, 7:19 AM
RZK 022
RZK 022 - avatar
+ 4
hasty is right , you can make it using any type of sorting and then simply displaying the second element of the array by using a[1].
17th Sep 2017, 7:23 AM
RZK 022
RZK 022 - avatar
+ 3
run in in c++
17th Sep 2017, 7:18 AM
RZK 022
RZK 022 - avatar
+ 1
what is wrong with my code but.
17th Sep 2017, 7:22 AM
Shantanu Shinde
Shantanu Shinde - avatar
+ 1
This version does not modify the order of data, you can use this version (it also go through the array only once) #include <stdio.h> /*for random*/ #include <stdlib.h> #include <time.h> #define SIZE 10 int main(){ int a[SIZE], min[2]; unsigned i; if(SIZE >= 2){ /*randomely initializing the array*/ srand(time(0)); puts("Your array is :"); for(i = 0; i < SIZE; ++i){ a[i] = rand(); printf("%d\n",a[i]); } putchar('\n'); /*now we find the second minimum without changing the array*/ if(a[0] > a[1]){ min[0] = a[1]; min[1] = a[0]; }else{ min[0] = a[0]; min[1] = a[1]; } for(i = 2; i < SIZE; ++i){ if(a[i] < min[1]){ if(a[i] < min[0]){ min[1] = min[0]; min[0] = a[i]; }else min[1] = a[i]; } } printf("Second minimum is %d\n",min[1]); }else puts("The array can't have a second minimum as its size is lower than 2."); return 0; }
17th Sep 2017, 8:07 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
no. code playground don't have c
17th Sep 2017, 6:43 AM
Shantanu Shinde
Shantanu Shinde - avatar
0
why is code not working but?
17th Sep 2017, 4:06 PM
Shantanu Shinde
Shantanu Shinde - avatar