the statement:
num = m1 = m2;
is wrong and it does not cause the three variables to have the same value. You need to assign m1 and m2 to num. You are overwriting the variable that you previously had read. Change it to:
m1 = num;
m2 = num;
Then, print out the m2.
EDIT:
As others found out, the -1 states for end of your input. Adding simple if statement solves the problem and for your input -169 is the second largest element.
Full code:
#include<stdio.h>
int main(){
int i, m1, m2, n, num;
puts("\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&num);
if(i==0)
{
m1 = num;
m2 = num;
}
else if(num == -1) /* if -1 was read, then terminate the loop. */
{
break;
}
else if(num>m1)
{
m2 = m1;
m1 = num;
}
else if(num>m2)
{
m2=num;
}
}
printf("%d\n",m2);
return 0;
}
For input:
7
-950 -588 -169 -187 -445 400 -1
and current code output is -169.
Another EDIT:
Ok, your code is wrong because of the scanf for number of elements. In future It would be helpful if you were more clear about your problems. I hope that following code will work for you.
#include <stdio.h>
int main(void)
{
int curr, second, first;
scanf("%d", &curr);
second = curr;
first = curr;
while (1) {
scanf("%d", &curr);
if (curr == -1) {
break;
}
if (curr > first) {
second = first;
first = curr;
}
else if (curr > second) {
second = curr;
}
}
printf("%d\n",second);
return 0;
}