LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 03-04-2011, 01:50 PM   #16
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948Reputation: 948

I know it is bad form to show the OP full code, but I think this might help our OP to understand the issues better.

First, here is code that uses a while loop to read any number of integers, then outputs the minimum.
(If you run it from command line, you can end the input either via Ctrl+D (aka EOF), or inputting anything other than an integer.)
Code:
#include <stdio.h>

int main(void)
{
    int     numbers = 0;
    int     minimum;
    int     number;

    /* While loop: Read a new integer into number,
     * until there is no more input (or it is not an integer).
    */
    while (scanf("%d", &number) == 1) {

        /* Test 'numbers' for zero, then increase it. */
        if (!numbers++) {
            /* 'numbers' was zero, so this is the first number. */
            minimum = number;

        } else
        if (number < minimum) {
            /* 'numbers' was not zero, but number is the new minimum. */
            minimum = number;
        }
    }

    if (numbers) {
        /* Numbers is nonzero, so there was at least one number input. */
        printf("Of the %d numbers input, %d was the minimum.\n", numbers, minimum);

    } else {
        printf("No numbers in the input.\n");
    }

    return 0;
}
In the above code, !numbers++ does two things at once: it tests if numbers is zero, and then increments it by one. Some think this is too tricky, and frown on using this, but it is quite common. (Note that !++numbers would first increase numbers by one, then test if it is zero.)

Here's the same code, but refactored using a for loop for exactly 'numbers' integers. Note that the for statement itself has format
for (initialization ; condition ; next_step) statement
where initialization is done unconditionally, only once, before anything else. The loop begins by testing the condition. If it is true, first statement is done, then next_step. Otherwise the loop ends. As always, statement can be just one statement, or it can be a block of statements enclosed in braces. initialization and next_step can contain multiple things separated by a comma in C99 at least.

I used the traditional i for the loop variable, since 'number' is already used for the integer value read from input.
Code:
#include <stdio.h>

int main(void)
{
    int     numbers = 10;
    int     minimum;
    int     number;
    int     i;

    for (i = 1; i <= numbers; i++) {

        /* Read new number into number. If it is not a number, break out. */
        if (scanf("%d", &number) != 1) {
            fprintf(stderr, "Cannot parse integer %d of %d!\n", i, numbers);
            break;
        }

        /* If this is the first number, it must be the minimum. Otherwise check. */
        if (numbers == 1)
            minimum = number;
        else
        if (number < minimum)
            minimum = number;
    }

    /* If i == numbers + 1, the for loop completed successfully. */
    if (i == numbers + 1) {
        printf("Of the %d numbers read, %d was the minimum.\n", numbers, minimum);

    } else
    if (i > 1) {
        /* We must have broken out of the loop early, but since i is where
         * the error occurred, we have read i-1 integers already.
         * Since i>1 (minimum i=2), we have read at least one integer.
        */
        printf("Of the %d numbers read, %d was the minimum.\n", i - 1, minimum);

    } else
        printf("No numbers read, so no minimum.\n");

    return 0;
}
Here's a third version of the same code, this time using a while loop to read only up to ten integers.
Code:
#include <stdio.h>

int main(void)
{
    int     numbers = 0;
    int     minimum;
    int     number;

    /* Only read up to ten numbers. */
    while (numbers < 10) {

        /* Increase the numbers count. It will then be 1 for the first number. */
        numbers++;
        
        /* Read new number into number. If it is not a number, break out. */
        if (scanf("%d", &number) != 1) {
            fprintf(stderr, "Cannot parse the %d. integer!\n", numbers);
            break;
        }

        /* If this is the first number, it must be the minimum. Otherwise check. */
        if (numbers == 1)
            minimum = number;
        else
        if (number < minimum)
            minimum = number;
    }

    if (numbers > 0)
        printf("Of the %d numbers read, %d was the minimum.\n", numbers, minimum);
    else
        printf("No numbers read, so no minimum either.\n");

    return 0;
}
I believe you'd learn most if you compile and run the above three programs, then compare, and try to understand the differences between them. (As far as I can tell, the code is pure C99, and compiles without even pedantic warnings.)

If you use Linux, and have a wide display, I recommend using diff --side-by-side file1 file2 to compare any two files side-by-side; append | less if the output is longer than the screen.

(A small off-topic note: "unified diffs", e.g. by running diff -Naprub thing1 thing2 are a very common way to describe differences between two different versions of the same source code. Lines beginning with - refer to the left thing, and lines beginning with + refer to the right thing; other lines are common to both. The command can compare entire directories, not just single files. If you intend to work with open source code, the ability to quickly understand unified diffs is of great value. And of course most patches are unified diffs.)

Last edited by Nominal Animal; 03-04-2011 at 01:52 PM.
 
Old 03-04-2011, 02:46 PM   #17
MrCode
Member
 
Registered: Aug 2009
Location: Oregon, USA
Distribution: Arch
Posts: 864
Blog Entries: 31

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by johnsfine
I understand it is easier to just write and show the answer than to try to figure out what concepts the OP needs explained. But for these homework posts it really isn't appropriate to show the answer.
Yeah, I have an easier time actually writing the code than explaining it. Sorry if the little snippet in my first post was inappropriate.

Quote:
Also, I agree with Anisha Kaul regarding the actual answer (the simpler version without an array is much better).
Yeah, it uses less memory, and is actually a bit faster, I think, than my first solution. Running two loops (one to store the args into an array, another to do the actual comparisons) will take more time than just running one to compare the args directly.

So yeah, when it comes to optimizing a program, I'm no expert.
 
Old 03-04-2011, 09:30 PM   #18
Aquarius_Girl
Senior Member
 
Registered: Dec 2008
Posts: 4,731
Blog Entries: 29

Rep: Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940Reputation: 940
j360,

Check this out: http://www.cprogramming.com/tutorial/c/lesson3.html

Last edited by Aquarius_Girl; 03-04-2011 at 09:48 PM.
 
Old 03-05-2011, 07:25 AM   #19
j360
Member
 
Registered: Jan 2010
Location: Maryland
Distribution: Ubuntu
Posts: 58

Original Poster
Rep: Reputation: 0
Thanks everyone , specially Anisha Kaul, your first example was very helpful. I'm just a novice over here
my professor didn't really go over "for loops", just one example which was very simple and not very helpful. Johnsfine sorry about forgetting to making my code readable. Quick question, I just got this ebook about C programming (C primer plus) which seems very helpful, do you guys recommend it?
 
Old 03-05-2011, 10:33 AM   #20
Telengard
Member
 
Registered: Apr 2007
Location: USA
Distribution: Kubuntu 8.04
Posts: 579
Blog Entries: 8

Rep: Reputation: 148Reputation: 148
Quote:
Originally Posted by j360 View Post
Quick question, I just got this ebook about C programming (C primer plus) which seems very helpful, do you guys recommend it?
I haven't read that.

I recommend The C Programming Language, second edition, by Brian Kernighan and Dennis Ritchie.

Any other book I've used for C programming is outdated, misguided, and teaches bad practice. It's the reason why the instructor at my college recommended against purchasing a textbook.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:54 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration