Thread: Question about Arrays and program flow

  1. #1
    Registered User
    Join Date
    May 2011
    Location
    Ontario, Canada
    Posts
    8

    Question about Arrays and program flow

    My challenge from C Programming of for the Absolute Beginner (which accurately describes me)

    Create a student GPA average calculator. The program should
    prompt the user to enter up to 30 GPAs, which are stored in a
    single-dimension array. Each time he or she enters a GPA, the
    user should have the option to calculate the current GPA
    average or enter another GPA. Sample data for this program is
    shown below.
    GPA: 3.5
    GPA: 2.8
    GPA: 3.0
    GPA: 2.5
    GPA: 4.0
    GPA: 3.7
    GPA Average: 3.25
    Hint: Be careful to not calculate empty array elements into
    your student GPA average.
    I have really no clue what I am doing. A friend of mine who worked for a decade as a computer programmer gave me this advice, which I tried to code:

    I asked him:

    I am trying to write a program that does the following:

    Code:
    While !inputdone
    {
    Accepts inputs into an array
    Checks for digits and rejects alpha
    Once there are more than two inputs stored in the array
        {
        offer the option to average inputs, or
        continue entering input
        }
    
    }
    He said:

    Code:
    While !inputdone
    {
    Ask for grade
    Check for numeric
    If numeric {
        Put input in array
        increment array index
        If two or more numbers have been entered {
            ask if user wants to average
            if answer is yes {
                average
                print result
                return(0);
            }
        }
    }




    And I have this so far (note I have not yet used iInputDone, and I don't even really know how I would do so - please be gentle, I know it is riddled with mistakes, but although a competent and logical person, I am crushed under the feet of computer programming)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int checkisdigit(int), i, iInput;
    char cInput;
    
    void main(void)
    {
        int iGrades[30] = {0}, iInput = 0, i = 0, iDoneInput = 0;
        char cAverage;
    
        printf("ENTER STUDENT GRADES\n");
        system("pause");
        system("cls");
    
    
        while (!iDoneInput)
        {
            entergrade:
            system("cls");
            iInput = 0;
            printf("\nPlease enter a grade: ");
            scanf("%c", &cInput);
    
            if (checkisdigit(cInput))
            iInput = cInput - '0';
            else
            goto entergrade;
    
            for (i = 1; i <= 30; i++);
            iGrades[i] = iInput;
    
            {
                if (i >= 2)
                {
                    calculateaverage:
                    printf("\nCalculate (A)verage?");
                    scanf("%c", &cAverage);
                {
                    if (!checkisdigit(cAverage))
                    {
                        if ((cAverage == 'A') || (cAverage == 'a'))
                        {
                            printf("\nAverage is %d", iGrades[i] += 0 / i);
                            return 0;
                    } // end if (cAverage == A)
    
                    else
                    goto entergrade;
                }  // end if (!checkisdigit)
    
                    else
                    goto calculateaverage;
            } // end calculateaverage
    
        } // end if i>2
    
    } // end for
    
    } // end while
    
    } // end main
    
    
    /*******\
    Functions
    ********/
    
    int checkisdigit(int iMyDigit)
    {
        if ((iMyDigit >= '0') && (iMyDigit <= '9'))
        return 1;
        else
        return 0;
    } // end checkisdigit

    The main problem is this: In runtime I enter a value but it displays the (A)verage? question for a split second, even after the first entry. And I have no idea how to check for a digit, then accept the value into the array.


    Please teach me! Thanks in advance.

    David
    Last edited by David.Mary; 06-25-2011 at 04:00 PM.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Checking for digits is easy... just include ctype.h and use the standard isdigit() library function...

    Code:
    #include <ctype.h>
    
    int main (void)
      { int x, y; 
         char input[80];
         int number = 0;
    
        // get stuff from user... (fgets() works well)
    
         // check for all digits.
         y = strlen(input)
         for (int x = 0; x < y; x++)
           { if (! isdigit(input[x]))
               { printf ("Entry Error!  Numbers only!"); 
                  exit (1); } }
    
         // here we assume it's all digits
         sscanf(input, "%d", number)
         // process number here
    
         return 0; }

    It would seem your primary issue here is not so much writing code, you seem to have a pretty decent idea of that... Where your problem appears to lie is with program design. Before you start coding you should sit down with pencil and paper and work out a step by step procedure to solve the problem. Never mind trying to write C code... just figure out how to solve the problem. Next you should try to simplify your solution to it's minimum nuber of steps... Once you can write the solution in your native language, then you should begin designing your C code...

    Look for standard library functions whenever you can (no need to reinvent the wheel) and write functions for anything that either A) needs private variables or B) is repeated in your code. In your case getting the input is an excellent candiate for a function... you could make it read a string, validated it as all digits, extract an integer (or float, as you need) from the string and actually return the number back to your main program.

    So, summarizing, two bits of advice...

    1) Understanding the problem is always the first step in creating a solution... There is no programmer, anyplace on this planet, no matter how experienced or skilled, who can successfully code the solution to a problem he or she does not understand.

    2) Think in smaller blobs. A program is not one continuous run of code. It is the sum of many smaller bits of code that work together to act out the solution to your problem.
    Last edited by CommonTater; 06-25-2011 at 04:42 PM.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I have really no clue what I am doing.
    That's unfortunate. Perhaps you should work your way through the examples and understand the lessons in the book before trying to write the code. Practice the simple stuff first, then start putting it all together. If you have no clue what you're doing, then that means you're not ready for this program yet.

    Please teach me!
    That's a tall order. I can't help you there, but I'll give you some advice on the questions you asked that will make sense when you start understanding your code better.

    ---

    In runtime I enter a value but it displays the (A)verage? question for a split second, even after the first entry.
    That is because first, your program runs this line:

    Code:
    scanf("%c", &cInput);
    This reads a character from "stdin" and places it into the variable "cInput." However, "scanf()" does not read the newline character (when you press enter) and so you have '\n' hanging in the buffer. Fast forward to the next input line ...

    Code:
    scanf("%c", &cAverage);
    ... and it reads that '\n' that was waiting in the buffer. Hence, it executes before the user is able to input a new value.

    So we have the newline character hanging out in the buffer after "scanf()" is executed. Perhaps if you follow this with some kind of command that can get the newline character out of the buffer, the next "scanf()" function will work the way you expect.

    And I have no idea how to check for a digit, then accept the value into the array.
    But you seem to have an idea how to check for a character and put it into a variable...

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    My, my....where to begin:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int checkisdigit(int), i, iInput;
    char cInput;
    You should move your variables inside of your main function. There is no need for global scope here.

    Code:
    void main(void)
    The main function always needs to return an int. Read about why void main is wrong

    Code:
    system("pause");
    system("cls");
    I wouldn't worry about this "fancy" stuff until you learn some basic C.

    There is never a reason to use goto. Sit down, think about what you want to do and restructure your code to prevent this. I believe the psuedocode your friend suggested is close enough to go with.

    Why did you include the ctype library if you aren't going to use anything in it. Hint: There is already a built in function, maybe you should take a look at isalpha() and isdigit() functions. The FAQs on this site are cool. Also I would read up on atoi().

    Look through that stuff and maybe even some of the other tutorials on this site and then repost some revised code. I am sure we will all help. What we will not do is to take spaghetti code that is broken and do a complete rewrite.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by AndrewHunter View Post
    There is never a reason to use goto.
    Well, actually there is... but this ain't it.

  6. #6
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Fair enough.......I have only ever seen it with error trapping. Which as you pointed out is not our case here. Thanks for keeping me honest.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by AndrewHunter View Post
    Fair enough.......I have only ever seen it with error trapping. Which as you pointed out is not our case here. Thanks for keeping me honest.
    Not to worry... if not me it would have been one of the others.

    I was thinking about how it gets used as a pseudo-finally clause with errors to make sure memory cleanup happens.
    (Although I much prefer using the SEH in Pelles C for that)

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Isn't that the truth....

    I enjoy that in the atmosphere here though, it helps satisfy my OCD.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by AndrewHunter View Post
    Isn't that the truth....

    I enjoy that in the atmosphere here though, it helps satisfy my OCD.
    Y'know... there are times when I really get frustrated by these picky old curmudgeons.
    But in all truth I've learned more here than from anywhere else...

  10. #10
    Registered User
    Join Date
    May 2011
    Location
    Ontario, Canada
    Posts
    8
    I'm reading what you recommended AndrewHunter, and it's definitely opening my eyes. All of you guys are a great help! Thank you all for your very good points. I can see that I will learn a lot here too.

    And thank you for your patience and good counsel. I can't tell you how much I appreciate it. I have no teacher; I'm not in school, but trying to learn this stuff on my own while working a non-related (and non-technical) job, in the hope of using my intellect to make a living, rather than my unskilled labour. My aforementioned friend helps when he can, but he is very busy and lives across the continent.

    I will post again on Monday, hopefully with my revised code.

  11. #11
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    We look forward to seeing it. Here is another tutorial to take a look at.

    -Happing Coding
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  12. #12
    Registered User
    Join Date
    May 2011
    Location
    Ontario, Canada
    Posts
    8
    Andrew, this last tutorial you posted is exactly what I need. My friend told me to read K&R, but I ditched it for C Programming for the Absolute Beginner by Michael Vine for the very reason enunciated in the link you gave:

    too many of my students found K&R a bit too technical for an informal, introductory course
    I will be putting an indeterminate hold on the above program and Michael Vine's book, and will instead work through K&R with the website you just gave me.

    Thanks again.

  13. #13
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    I am glad to have helped. Feel free to post questions when you need to.


    -Happy Coding.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MessageBox stops program flow
    By Ducky in forum Windows Programming
    Replies: 3
    Last Post: 06-20-2011, 10:40 PM
  2. Program flow
    By Ducky in forum C++ Programming
    Replies: 5
    Last Post: 02-11-2010, 12:04 PM
  3. Program flow
    By Ducky in forum C++ Programming
    Replies: 4
    Last Post: 04-20-2009, 08:27 AM
  4. Buffer Over Flow with string Arrays
    By vlrk in forum C Programming
    Replies: 1
    Last Post: 06-24-2008, 07:16 AM
  5. Program flow
    By Ducky in forum C++ Programming
    Replies: 22
    Last Post: 01-09-2008, 11:18 AM

Tags for this Thread