Help with flawed algorithm?

This is a discussion on Help with flawed algorithm? within the C Programming forums, part of the General Programming Boards category; Hey mates, I'm writing a program I was told to, where you enter a matrix (rows and columns), and it ...

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    23

    Help with flawed algorithm?

    Hey mates,

    I'm writing a program I was told to, where you enter a matrix (rows and columns), and it needs to calculate it like this:

    1 2 3
    + + +
    1 1 1

    solution is: 2 3 4

    Now, notice that for this matrix, the number of rows entered was 2! and columns 3.

    So the operands are like an extra row that the user enters. The number of rows refers the one that contain integers.

    My algorith works perfectly except for one little flaw which I can't seem to debug - if you enter for rows "2", it won't stop untill you feed in 3 rows. I've been through my algorith and I can't see why...

    I'm adding the input loop if you guys can spot it:

    Help will be much appreciated!

    Code:
    printf("Enter the number of rows and columns:\n");
    
    
    scanf("%d %d", &row, &column);
    fail=0;
    
    
    while( row<1 || row > 99 || column > 99 || column < 1)
    {
    
    
        printf("Enter a valid number of rows and columns:\n");
        scanf("%d, %d", &row, &column);
    }
    
    
    row+= (row-1);
    int matrix[row][column];
    
    
    
    
    printf("Enter the matrix: \n");
    i=0;
    j=0;
    fail=0;
    
    
     while (i< (row)) //Input the matrix!!!
     {
         j=0;
         while (j<column)
         {
            if ((i%2)==0)
            {
                scanf("%d ", &input);
                matrix[i][j] = input;
                if (input==' ')
                {
                    continue;
                }
                if (input=='\n')
                {
                    if (j==(column))
                    {
                        printf("\n");
                        break;
                    }
                }
            }
            if ((i%2)!=0)
            {
                oper=getchar();
    
    
                if (oper==' ')
                {
                    continue;
                }
    
    
                if (oper=='-' || oper=='+' || oper=='/' || oper=='*')
                {
                    matrix[i][j] = oper;
                }
                else
                {
                    fail=1;
                }
            }
            j+=1;
         }
         i+=1;
    
    
     }

  2. #2
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Please explain line 17.
    Code:
    row+= (row-1);
    Why do you want to change the value held by `rows`?
    What do you want to achieve with it?


    EDIT: Never mind the above

    Don't mix scanf() and other input functions. Either always use scanf() or never use scanf().
    Last edited by qny; 12-07-2012 at 05:07 AM.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    Ok I seem to have found it - it's in line 36 - scanf("%d ", &input);

    but if I delete the space after %d, if I put in any operand that's valid it's taking me into the "else" on line 66...

  4. #4
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    Quote Originally Posted by qny View Post
    Please explain line 17.
    Code:
    row+= (row-1);
    Why do you want to change the value held by `rows`?
    What do you want to achieve with it?
    Since I'm getting a number of rows, let's say 3, remember the operands rows aren't included so I'm adding them so I'll be able to put 'em into the array...






  5. #5
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    Ok so basically, the problem is somewhere in line 36. if I put in scanf("%d ", &input); then the input loop will be all good except for that extra line that matrix will have to get, and I don't want that.

    If I delete that "space" after %d then the matrix will get the "\n" input and will count it as an invalid operand, thus getting me into the fail=1 and throwing my whole code to hell...

    Any suggestions?

  6. #6
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    And another question - how can I detect EOF with scanf?

  7. #7
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    Just the ref :
    Return Value
    On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

    If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

    If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  8. #8
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Gal Abir View Post
    Any suggestions?
    I did offer a suggestion with an edit. Maybe you didn't see it.

    Do not mix scanf() and other input functions.
    Best way (the one with most control) is to read lines with fgets() and then deal with the lines as appropriate (directly char-by-char, use strtol(), strtod(), interpret from the line with sscanf(), ...)

  9. #9
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    I understand... Just notice I Can only use functions from stdio.h

    Is there a way, with getchar(), to get more than 1 char? Like, if I want to input "13".

    And what's fgets?

    I'm really lost... IS there a way to identify \n with scanf? as I was saying, everything works PERFECTLY in my code except that one thing.... I need to know how to recignize a \n when I get one...

  10. #10
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    Read these :
    scanf

    fgets
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  11. #11
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Gal Abir View Post
    Is there a way, with getchar(), to get more than 1 char? Like, if I want to input "13".
    No, getchar() reads a single character. What you can do with getchar(), is manage the input little by little and build larger parts as you go along. Remember to properly terminate the strings!

    Quote Originally Posted by Gal Abir View Post
    And what's fgets?
    fgets() reads a complete line from input, ENTER and all. With the complete line available to your program you can then use a pointer to somewhere in the line and parse the input as needed.

    Quote Originally Posted by Gal Abir View Post
    Is there a way to identify \n with scanf?
    No, not really. I mean: you can use "%c" or "%[...]" and identify whitespace, but the work that requires is more than reading isolated characters with getchar().

  12. #12
    Registered User
    Join Date
    Dec 2012
    Posts
    23
    Sorry guys,

    I read the comments and that fgets guide and I didn't understand it :/

    Can anyone care to explain?

  13. #13
    Registered User
    Join Date
    Jun 2011
    Posts
    2,192
    Code:
    fgets ( char * str, int num, FILE * stream );
    //      |           |        |
    //      |           |        This is where you want to read the
    //      |           |        string from.  If you want to get it
    //      |           |        from the user, the argument should be
    //      |           |        the standard input stream (stdin).
    //      |           |
    //      |           This restricts the length of the string read,
    //      |           and only allows "num-1" characters to be read.
    //      |           Any characters beyond the limit are not taken
    //      |           from the input stream.  This argument is the
    //      |           reason why "fgets()" is strongly recommended;
    //      |           the old "gets()" function has no such limitation,
    //      |           and will happily read characters from the stream
    //      |           even if it overflows the buffer where the string
    //      |           is to be stored.  This could cause errors in the
    //      |           program, and can also be a security vulnerability.
    //      |
    //      This is the destination, where you want to put the string when
    //      it is read.  For your purposes, this will likely be a character
    //      array (i.e. "charArray[50]").  You can simply pass the name of the
    //      array (i.e. "charArray"), as in this case, the name of the array
    //      will behave as a pointer to the first element of that array.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Gal Abir View Post
    Ok so basically, the problem is somewhere in line 36. if I put in scanf("%d ", &input); then the input loop will be all good except for that extra line that matrix will have to get, and I don't want that.

    If I delete that "space" after %d then the matrix will get the "\n" input and will count it as an invalid operand, thus getting me into the fail=1 and throwing my whole code to hell...

    Any suggestions?
    Give scanf() a char to chew on - throw it a bone:

    Code:
    scanf("%d%c", &num,&bone);
    char bone is just garbage, but it can be very useful garbage, even though it's never used. (scanf() also has a *format suppressor, but this works just as well, and is simple).

  15. #15
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Quote Originally Posted by Adak View Post
    Code:
    scanf("%d%c", &num,&bone);
    If the user types "<SPACE> <4> <2> <SPACE> <ENTER>" this will not consume the <ENTER>.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-20-2011, 09:58 PM
  2. Replies: 3
    Last Post: 06-23-2010, 06:50 AM
  3. algorithm
    By osheghi in forum C++ Programming
    Replies: 0
    Last Post: 05-01-2009, 10:07 AM
  4. O(n) algorithm
    By wu_weidong in forum C Programming
    Replies: 16
    Last Post: 10-05-2005, 05:52 PM
  5. my grandfather's chess algorithm can beat your grandfather's chess algorithm...
    By doubleanti in forum A Brief History of Cprogramming.com
    Replies: 22
    Last Post: 08-17-2001, 06:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21