Thread: Find the minimum number *homework*

  1. #1
    Registered User
    Join Date
    Jun 2014
    Posts
    8

    Find the minimum number *homework*

    Hello,
    I am new this is my first post and was hoping someone may be able to direct me to my error, what I am asked to do,

    Write a C program that takes multiple integers from the user and finds the minimum value. The numbers
    entered by the user are positive integers. When the user is done entering all the numbers, the user enters
    the sentinel value of -1.
    This is a sample output. Notice how the program prints a counter (1, 2, 3, ) to help the user keep track of
    how many numbers were entered so far. Include this feature in your program.

    I have tried different ways to get the result from while loops, do while, and if-else statements. We have not done any max/min problem in class and the book was kind of vague. We have not learned arrays yet in class and I can't figure a way to compare the integers the user inputs as it is an infinite(from what I am reading) amount aloud. The problem I am seeing is the loop works and stops with the sentinel value but the INT_MIN is using the sentinel value. I also have not addressed the input of negative numbers yet with the first program I wrote, maybe one of my problems.
    Thank You for any help,

    Code:
    /*File:HW2Q3.c, 
    A C program that takes multiple integers from the user and finds the minimum
    value. The numbers entered by the user are positive integers. When the user
    is done entering all the numbers, the user enters the sentinel value of -1.*/
    /*header files*/
    #include<stdio.h>
    #include<limits.h>
    /*****start program*****/
    int main()
    {
        /*****declare variables*****/
        int a;//user input
        int counter=0;//counts entries
        INT_MIN;//for minimum value
        int sentinel;//program stops asking for input
        
        a=4;//initialize start value so while loop starts
        sentinel=-1;//initialize sentinel value
        INT_MIN != sentinel;/*****tried to use this statement to not
                     include -1 in minimum value (didn't work)*****/
         
        printf("Finding the minimum...\n");
        printf("Enter integers (-1 to finish)\n");             
        while(a!=-1)//start while loop to take user input and keep track of input
        {
                    
                    printf("%d integers: ",counter+1);//prints to screen
                    scanf("%d",&a);//user input
                    counter=counter + 1;//counts the entries from user
                    
        /******I have tried this outside loop and same result as inside loop******/      
                    if(a==-1)//start of if statement,(a) is compared to -1 print message
                    printf("INT_MIN=%d\n",a);//prints minimum value entered
         
    }//end while loop
        
            
                  
    system("pause");//pause program for user
    return 0;//terminate program
    }       //end main
    I have also tried this way as well, min value still comes back as -1 the sentinel value, and the else statement is being ignored. I am sure it is something silly but I am lost and confused at this point.

    Code:
      /*File:HW2Q3.c, 
    A C program that takes multiple integers from the user and finds the minimum
    value. The numbers entered by the user are positive integers. When the user
    is done entering all the numbers, the user enters the sentinel value of -1.*/
    /*header files*/
    #include<stdio.h>
    #include<limits.h>
    
    /*****start program*****/
    int main()
    {
        /*****declare variables*****/
        
        int a;//user input
        int counter=0;//counts entries
        INT_MIN;//for minimum value
        
        
        a=4;
        if(a>=0)
        {
        
        while(a!=-1)//start while loop to take user input and keep track of input
        {
                    
                    printf("%d Enter numbers: ",counter+1);//prints to screen
                    scanf("%d",&a);//user input
                    counter=counter + 1;//counts the entries from user
                    
                    if(a==-1)
                    printf("INT_MIN=%d\n",a);//prints minimum value entered
                              
                    
    }//end while loop
    }
       
        else 
         {          
                    printf("Use only positive numbers or enter -1 to finish input\n");
         } 
                               
                  
    system("pause");//pause program for user
    return 0;//terminate program
    }       //end main

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Please point to the line you declare the variable that is supposed to hold the minimum value entered.
    What type is that variable?
    What is that variable name?

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Jun 2014
    Posts
    8
    OK I think what your asking is what I don't have? I have (int a) which I believe is holding the integers that the user is inputting then magically, I expect INT_MIN to pull the smallest number that was inputted. Type would be integer?

    Code:
    int a;//user input
    INT_MIN;//for minimum value
    
    printf("INT_MIN=%d\n",a);//prints minimum value entered
    Sorry homework has gone past my understanding and I am struggling to keep up and understand what I am doing and why I am doing it. So you might have to be more blunt in what I need to look up urg sorry
    Thank You,
    Marie

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Why do you think this line will compile and what do you think it does?

    Hint: It should NOT compile.

    Code:
    INT_MIN;//for minimum value
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  5. #5
    Registered User
    Join Date
    Jun 2014
    Posts
    8
    Ok I think that just tells you the size of the different types int, float, long long etc. lol, completely lost my mind back to the book, I did say I was hoping it was a magically answer to my problem.
    Thank You
    marie

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You have identified your confusion with INT_MIN -- that's good. Another point to clarify, if you haven't figured it out yet, is this:
    Code:
    INT_MIN;
    does nothing. It's like saying 42; Yes, there is a value associated with INT_MIN, but you don't store that value anywhere, nor do you make any decisions about the value (not part of a if condition or a loop condition). Similarly
    Code:
    INT_MIN != sentinel;
    Is pointless. It does the comparison checking for INT_MIN not equal to sentinel, resulting in a true/false value. That value is never used though, so it's pointless. If you turn up the warning level on your compiler (-Wall option for GCC/MinGW, else you have to check your compiler docs) it should spit out a warning saying something like "foo.c:3: statement with no effect" -- that is, you have a pointless statement on line 3 of the file foo.c that you should fix or remove.

    Sometimes it helps to read your code aloud in English or whatever your natural language is. Something like the following:
    Code:
    if(a==-1)
        printf("INT_MIN=%d\n",a);//prints minimum value entered
    would sound like
    If a is equal to -1, then print a as the minimum value entered
    Do you see where the logic flaw is? You print the value of a, but you only do so when the if condition is true, i.e. when a is -1. Of course it always prints -1, since that's exactly what you told it to do .

    As for the second code example, where the else is being ignored, that's also simple. Only one of the if or the else can be executed. If the "if" condition is true, the if part is executed and the else part is ignored skipped. If the "if" condition is false, the if part is skipped and the else part is executed. So again, reading the following code aloud:
    Code:
    a = 4;
    if (a >= 0)
    {
        // do some stuff
    }
    else
    {
        // do some other stuff
    }
    Sounds like: "Set a to 4. Compare a to 0. If a is greater than or equal to 0 (which it is, since 4 >= 0), then do some stuff. Otherwise, do some other stuff." See any logical flaw there? How can the else ever be executed?

    I strongly suggest using clear, consistent indentation that accurately reflects the logical structure/flow of your program (see this link). It makes it much easier to follow the logic of your program.

    Try working this out by hand, with paper and pencil. You can't program a computer to do a task, if you don't know how to do the task yourself. Imagine you are sitting down with your friend, and you are playing the part of the computer, while your friend says numbers to you. How would you keep track of the smallest number? How would you know when to stop? Pay careful attention to all the little steps you take, every time you check the value of a number, every you friend gives you a value that is the new minimum value. Write out every little step by hand on paper and pencil. Start in your native language. Then convert it to pseudo code, which resembles C code, but don't worry about syntax particulars, variable declarations, etc. Just get the logical structure correct. Then convert the pseudo code to C code, little by little, testing as you go. Start by just being able to read a list of numbers and stopping when you see your sentinel value. Then add the code for determining the minimum value entered (excluding the sentinel).

    A couple more small pointers:

    1. I prefer do-while loops for user input, since they always execute the body at least once, and you always want to ask the user for input at least once before doing anything.
    2. Consider using a #define with a descriptive name for your sentinel value. It makes your code easier to read and modify. You can change the sentinel value by changing just one line (the #define) instead of many places.

  7. #7
    Registered User
    Join Date
    Mar 2011
    Posts
    596
    Quote Originally Posted by mariegrdnr View Post
    Ok I think that just tells you the size of the different types int, float, long long etc. lol, completely lost my mind back to the book, I did say I was hoping it was a magically answer to my problem.
    Thank You
    marie
    INT_MIN is the minimum (most negative) value that an int can hold. It's a predefined value (a C macro definition) and it's not going to be useful here.

    You need to declare a variable to store the minimun value, eg, 'min'. You already have the input values stored in 'a', as the values are input.
    Then all you need to do is compare 'a' to 'min' and assign 'min' a lower minimum value if a value lower than 'min' it is input. You do this inside
    the loop that inputs the user values.

    Also, since all the input values are positive integers, initialize 'min' to -1. When the first value of 'a' is input, 'min' will then start out as equal to 'a'.

    Remember that a statement is only executed as it is encountered in a program. A statement that assigns a value will only do so when the statement
    is encountered. The assignment will not happen automatically throughout the program.

    -

  8. #8
    Registered User
    Join Date
    May 2014
    Posts
    12
    Did your teacher teach you how to write an algorithm before writing code? It'd be VERY helpful here and for all future programming assignments.

  9. #9
    Registered User
    Join Date
    Jun 2014
    Posts
    8
    Sorry it took so long, first thank you for all your help this is what I ended up with
    Code:
    /*File:HW2Q3.c, 
    A C program that takes multiple integers from the user and finds the minimum
    value. The numbers entered by the user are positive integers. When the user
    is done entering all the numbers, the user enters the sentinel value of -1.*/
    /*header files*/
    #include<stdio.h>
    /*****start program*****/
    int main()
    {
        /*****declare variables*****/
        int integer;//user input
        int counter=0;//counts entries
        int min;//minimum value
        int sentinel=-1;//sentinel value 
        
        min=10000;//declare min to anything other then sentinel
        printf("Finding the minimum...\n");//print message
        printf("Enter integers (-1 to finish)\n"); //print message 
        /*start while loop to take user input and keep track of input and stop if -1
        is entered*/  
             
        while(integer!=sentinel)//while loop runs loop til sentinel value is entered
        {
                    
                    printf("%d integers: ",counter+1);//prints counter to screen
                    scanf("%d",&integer);//user input of integers
                    counter=counter + 1;//counts the enteries from user 
                    if(integer!=sentinel){//if statement so that it does not use sentinel value
                            if(integer<min){//if statement to compare new numbers entered
                            min=integer; //replace min with new number 
                             
                            }//closes integer<min if statement
                            }//closes integer!=sentinel if statement
         }//end while loop
          printf("The minimum integer entered= %d\n",min);//prints the min number         
    system("pause");//pause program for user
    return 0;//terminate program
    }       //end main
    if anyone has time let me know if there is statements that are not correct or garbage that may not be needed, I tried to make sure that all of it has a purpose and that I understand the purpose of the statement.
    again thank you
    marie

  10. #10
    Registered User
    Join Date
    Jun 2014
    Posts
    8
    Quote Originally Posted by xrayextra View Post
    Did your teacher teach you how to write an algorithm before writing code? It'd be VERY helpful here and for all future programming assignments.
    summer class moving fast, he glossed over it with a couple examples, not his fault garbage in garbage out up to me to pay closer attention and work harder

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Much, much better overall. First point to make, however, is that you should compile at the maximum warning level:
    Code:
    $ make foo
    gcc -Wall -ggdb3 -pedantic -std=gnu99 -O0 -o foo foo.c -lm -lpthread -lrt
    foo.c: In function ‘main’:
    foo.c:36:5: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
    That means you didn't #include the header that defines the system() function. You need to add #include <stdlib.h> at the top of the file. It's worth noting that the pause command, which you run via the system() function, is Windows-specific. Thus, it causes an error message when I run your program on my Linux system. It's fine if you want or need to use it for class, just be aware that it is not portable.

    Once you fix the #include, the algorithm works, but with one caveat: it only works if some numbers are smaller than 10000. If I enter 99999 and 10001 as my integers, your program will incorrectly report 10000 as the minimum entered integer. I suggest you use the constant INT_MAX provided by your implementation as the starting min value (it's the counterpart to INT_MIN, which you already know about). This way, no matter what int I enter, it will always be less than or equal to min, so if I only enter very large numbers, your program will still work. Make sure you #include <limits.h> to have access to it. Use INT_MAX for your starting min value.

    Your variable names are much better, and you have comments that explain the code, which makes it easier to read, understand and maintain, which are very important features of any software project. Your indentation is still a bit lacking, but some of that may be from copy-pasting into the forum. Using only spaces for indenting, instead of tab or a mix of spaces and tabs, usually helps with this.

    You do have too many comments, however. This is not unusual when you are new, either because it is a requirement for the assignments (to ensure students do write some comments), or it helps you understand what you are doing. However, in general, you don't want to comment every line. Definitely don't comment the obvious, like "// print message". You should strive to write clear, easily-understood code that is as "self-documenting" as possible. Good variable/function/type names, and small functions with clear logic and structure take care of much of that. Comments should only be used to explain code that is not obvious, for example: how a complicated algorithm works; why you are doing something the way you are, like choosing an awkward/non-intuitive way of doing something to avoid a bug in the implementation (unlikely, but I've seen it happen).

  12. #12
    Registered User
    Join Date
    Jun 2014
    Posts
    8
    Quote Originally Posted by anduril462 View Post
    Much, much better overall. First point to make, however, is that you should compile at the maximum warning level:
    will look to see how to change that.
    Quote Originally Posted by anduril462 View Post
    That means you didn't #include the header that defines the system() function. You need to add #include <stdlib.h> at the top of the file.
    Yea, he doesn't go over headers, so I have to try to look them up myself, thank you for letting me know.
    Quote Originally Posted by anduril462 View Post
    It's worth noting that the pause command, which you run via the system() function, is Windows-specific. Thus, it causes an error message when I run your program on my Linux system. It's fine if you want or need to use it for class, just be aware that it is not portable.
    Good to know, I had seen Getchar() or something along those lines in others work, but he hasn't taught it so I didn't use it.
    Quote Originally Posted by anduril462 View Post
    Once you fix the #include, the algorithm works, but with one caveat: it only works if some numbers are smaller than 10000. If I enter 99999 and 10001 as my integers, your program will incorrectly report 10000 as the minimum entered integer. I suggest you use the constant INT_MAX provided by your implementation as the starting min value (it's the counterpart to INT_MIN, which you already know about). This way, no matter what int I enter, it will always be less than or equal to min, so if I only enter very large numbers, your program will still work. Make sure you #include <limits.h> to have access to it. Use INT_MAX for your starting min value.
    Will do, but I do not understand why teacher said it does not matter what I set it to as long as it is not sentinel value? I must not understand something here.?
    Quote Originally Posted by anduril462 View Post
    Your variable names are much better, and you have comments that explain the code, which makes it easier to read, understand and maintain, which are very important features of any software project. Your indentation is still a bit lacking, but some of that may be from copy-pasting into the forum. Using only spaces for indenting, instead of tab or a mix of spaces and tabs, usually helps with this.
    will work on it still getting used to compiler
    Quote Originally Posted by anduril462 View Post
    You do have too many comments, however. This is not unusual when you are new, either because it is a requirement for the assignments (to ensure students do write some comments), or it helps you understand what you are doing. However, in general, you don't want to comment every line. Definitely don't comment the obvious, like "// print message". You should strive to write clear, easily-understood code that is as "self-documenting" as possible. Good variable/function/type names, and small functions with clear logic and structure take care of much of that. Comments should only be used to explain code that is not obvious, for example: how a complicated algorithm works; why you are doing something the way you are, like choosing an awkward/non-intuitive way of doing something to avoid a bug in the implementation (unlikely, but I've seen it happen).
    Yes I know some of it was silly, wouldn't normally do it but my homework grade was average last time and he gives no feed back so I figured I would add comments to see if that helped grade as last homework was much easier (i.e. print hello world) then this one.
    Thank you for the input it helps a ton!
    Thanks
    Marie

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    As for the compiler warnings, it depends on the compiler. If you Google "<compiler name> maximum warnings" or something similar, you should find plenty of solutions. I always suggest enabling all warnings since, while a warning is not an actual violation of the C language, it is usually an indication of bad, suspect or error-prone code.

    I also don't know why the teacher said "anything other than the sentinel". Initializing min as the sentinel value is problematic though, and INT_MAX would be better. The reason to use INT_MAX is because you must start min with the largest possible value. That way, if the user enters a smaller value, min becomes that smaller value when you do min=integer; If the user enters the value equal to INT_MAX, and min still has the initial value of INT_MAX, it's okay since (so far) that is the smallest number the user entered. The user can't enter an int larger than INT_MAX since it's the maximum int. Perhaps your teacher says 10000 is okay since s/he doesn't plan on entering such large values, maybe s/he will only enter numbers between 0 and 100 or 0 and 1000. min must simply start with a value equal to or greater than the largest value the user will enter.

    I forgot to mention it last time, but I'm not actually a big fan of the variable 'integer'. It's a bit generic and, simply describes the type of the variable/data instead of it's purpose. Imagine you wanted to change this program to accept floats or doubles. Now you either have an inaccurate variable name or you have to change it in a dozen places in just this small program -- a big program would be a giant pain. Instead, try to describe the variable's purpose, or what it represents. Something like user_number or user_input would probably be a bit better.

  14. #14
    Registered User
    Join Date
    Mar 2011
    Posts
    596
    I mistakenly said:

    Also, since all the input values are positive integers, initialize 'min' to -1.

    It should of course be initialized to INT_MAX as anduril462 said.

    Sorry if it caused any confusion or extra work.

    -

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 03-11-2013, 12:47 PM
  2. Find minimum in an array, using recurssion.
    By Avenger625 in forum C Programming
    Replies: 12
    Last Post: 02-13-2012, 11:00 PM
  3. Finding maximum and minimum number in 2D array
    By wonderwall in forum C Programming
    Replies: 4
    Last Post: 10-23-2011, 10:21 PM
  4. Minimum/maximum number problem. Please help!
    By PYROMANIAC702 in forum C Programming
    Replies: 43
    Last Post: 07-15-2011, 12:28 AM
  5. find more than one minimum
    By saudi-vip in forum C Programming
    Replies: 3
    Last Post: 11-14-2008, 02:57 AM