# Simple program, simple problem

• 02-16-2011
KAUFMANN
Simple program, simple problem
Code:

```#include <stdio.h> int main(void){     int i,pos,num,minimum;     for(i=1;i<=5;i++){                         printf("Input an integer:");                         scanf("%d",&num);                         printf("\n");                         if(num<0){                                   minimum=num;                                   pos=i;                                   }                         }     printf("The smallest negative integer is %d and its position is %d",minimum,pos);     printf("Have a good one\n\n");     system("pause"); }```
Hello there.

So, this small little program is supposed to get 500 numbers from input, and then determine which one is the smallest negative. For instance, between 4 -2 -4 10 -23, the smallest negative number would be -2.

However it does not seem to work because it just prints out the last negative integer which went into the program.

Could someone enlighten me?
• 02-16-2011
anduril462
You are assigning minimum to every negative number in the sequence, and pos to it's position as well. You need to track the current maximum number less than zero. Something like:
Code:

```if num is less than zero and num is greater than the current maximum number less than zero     max_neg = num     pos = i```
Note you need to initialize max_neg and pos appropriately.
• 02-16-2011
CommonTater
Since you are only testing for <0 you will get the last negative number, not the smallest one.
Also testing if thisnum < lastnum will actually get you the most negative number not the least negative...

Try something like this, where lneg is your result...
Code:

```int num; int lneg = -1000000; if (num < 0)   { if (abs(num) <  abs(lneg))       lneg = num; }```
• 02-16-2011
anduril462
Oh yeah, and you told the compiler main will return an int, so why doesn't it. This can lead to problems.

As for Tater's example, or mine, you probably want to initialize lnum/max_neg to INT_MIN from limits.h.
• 02-16-2011
CommonTater
Quote:

Originally Posted by anduril462
Oh yeah, and you told the compiler main will return an int, so why doesn't it. This can lead to problems.

As for Tater's example, or mine, you probably want to initialize lnum/max_neg to INT_MIN from limits.h.

Good catch... both times!
• 02-16-2011
KAUFMANN
Very well then, I took Tater's suggestion, although it is not precisely what I wanted, and it worked out. Thank you guys.
Code:

```#include <stdio.h> int main(void){     int i,n,pos,num,limit;     limit=-1000000;     for(i=1;i<=5;i++){                       scanf("%d",&num);                       if(num<0 && num>limit){                               pos=i;                               limit=num;                               }                               }     printf("The smallest negative integer is %d at pos=%d",limit,pos);     system("pause");     return 0; }```