• C

GPA Comments using Switch/Case in Basic C

Hello!  It's late here around 11:32 but I've finished my GPA assignment and was wondering if you would take a peek and comment.  The assignment was a little vague and I tried to clarify by asking the instructor if I needed to only allow 20 students (I was thinking with a counter of some sort).

I asked : What do you mean by there are up to 20 students?
> That the loop will only
> allow 20 students or is continuous so that 20
> students can input their GPA
> of 0-4?
Instructor responded: The idea is that you learn to interpret what is being
said. A programmer's life is not just about writing
code, it is about understanding what the client wants
versus what they say.
This is a hint that your program needs to go into a
loop at least 20 times.

With that said, I went with a loop that would continue but asks for a new student or to exit.  See below and tell me what you think...=)  Do you really need the default at the end of the switch/case?

/*6/12/06, POS370, Susan Johnson Individual Assignment
*
*Write GPA program using if statement & switch case, include loop.
*There are up to 20 students in class with GPA of 0-4.
*If GPA is 4, display "Excellent Work".
*If GPA is 3, display "Good Work".
*If GPA is 2, display "Fair Work, Study Harder".
*If GPA is 1, display "Danger Will Robinson!".
*If GPA is 0, display "Were You Listening?".*/

#include <stdio.h>

main()
{

int gpa = 0;
int prompt;
int x = 0;
     
     while (x == 0)
     {/*begin while loop*/
         
     printf("\n******************FACULTY GPA COMMENT PROGRAM****************************\n\n");
     printf("\nWelcome Student! To read faculty feedback, \n");
     printf("\nEnter your GPA from 0 to 4: ");
     scanf("%d", &gpa);
         
          if (gpa >= 0 && gpa <=5)
          {/*begin if statement*/
         
          switch (gpa)
          {/*begin switch/case*/
               
               case 0:
                    printf("\n\tYour GPA is %d, WERE YOU LISTENING?!?",gpa);
                    break;
                         
               case 1:
                    printf("\n\tYour GPA is %d, Danger Will Robinson!",gpa);
                    break;
                   
               case 2:
                    printf("\n\tYour GPA is %d, Fair work, study harder!", gpa);
                    break;
                   
               case 3:
                    printf("\n\tYour GPA is %d, Good work!", gpa);
                    break;
                   
               case 4:
                    printf("\n\tYour GPA is %d, Excellent work!", gpa);
                    break;
                                       
               default:
                    printf("\n\tYou did not enter a valid GPA from 0-4\n");
                   
                   
     }/*end switch/case*/
         
     printf("\n\nFor new student, select 1, to exit select 2: ");
     scanf("%d", &prompt);
         
     if (prompt == 2)
     {/*begin if statement*/
     x=1;
     }/*end if statement*/
     
     }/*end if statement*/
     
     else
          printf("\n\n%d is not a valid GPA, Please enter your GPA from 0-4", gpa);
         
     }/*end while loop*/
     
          printf("\n\n********Be Sucessful! Do Your Homework and Study Hard!*********");
               
     getchar();

}/*end main program*/
Cabochick05Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
PaulCaswellConnect With a Mentor Commented:
Definitely above:

if ( condition )
{
 <code to execute if condition is true>
}
else
{
 <code to execute if condition is false>
}

although you dont need an 'else' part if you dont want one.

Paul
0
 
cryptosidCommented:
The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

So its not mandatory, but it is generally used to make your program more user friendly.

Here in your case it is for pointing out to the user if she/he enters a 'wrong' input.

Regards,
Siddhesh
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
fridomCEO/ProgrammerCommented:
IMHO you should start using subfunctions for certain tasks, and it seem appropriate to start about possible problems in your code. So I would go for

some function prompting for the grade.
example code (with error handling)
#include <stdio.h>

enum{SOME_LIMIT=512};

int prompt_for_grade (void) {
  char buf[SOME_LIMIT];
  char *pc = NULL;
  int grade;
  int i_rval;
 
  printf("\n******************FACULTY GPA COMMENT PROGRAM****************************\n\n");
  printf("\nWelcome Student! To read faculty feedback, \n");
  printf("\nEnter your GPA from 0 to 4: ");
  fflush(stdout); // get the output from the last printf
  pc = fgets(buf, SOME_LIMIT, stdin);
  if (NULL == pc) {
    fprintf(stderr, "Could not get input from the user, giving up\n");
    return -1;
  }
  i_rval = sscanf(buf, "%d", &grade);
  if (i_rval != 1) {
    fprintf(stderr, "Could not find a number in the input, check your input please\n");
    return -1;
  }
  return grade;
}


int main(void){
  int grade;
  grade = prompt_for_grade();
  if (grade >= 0){
    printf("your grade is: %d\n", grade);
  } else{
    fprintf(stderr, "Something has gone wrong while trying to get the grade\n");
  }
  return 0;
}

One functoin for the output you just give it the recevied grade. As written before the magic variables are not a good idea use #defines or enums for the grade grades

#define EXCEPTIONAL 6
# define WELL_DONE 5
....

Functions are there for  a very good reason. Try to get into their use.

Solve you problems one by the other. First do something run which you can rely on, the above prompt_for is IMHO a good example. It defends itself for strange data and can be seen as quite robust. Agreed, it tooks quite some lines for error handling, but that's how one must tackle C.

C is an extremly sharp tool. It's easy to cut of a finger and not terrible hard to cut off the whole hand. I know we (I mean the answeres here) do not stress that much enough. But I guess I will switch to nit-picking mode from now on ;-(

Regards
Friedrich

Regards
Friedrich



0
 
Cabochick05Author Commented:
Fredrich,
Thank you for your comments.  Please forgive me, but I think your answer is too advanced for my 3rd week of basic C!  I can follow it...sort of, but we have not been instructed to use much of what you have suggested.  In fact, this instructor has advised heavily against using anything we have not gone over in class which makes our programs very basic and simple.   (Remember my last question, where my instructor advised to remove #define as we have not learned it yet?)  

I have more programming classes coming up so I'm sure it will come in handy then!
Regards, Susan
0
 
Cabochick05Author Commented:
Thank you Siddhesh, your comment was very helpful.
Friedrich, I just noticed I mispelled your name earlier, fogive my oversight!
Susan
0
 
fridomCEO/ProgrammerCommented:
You'll say you do not have encountered self written functions?
I guess I'm too long away from university...

Ok, if you are using scanf then please check the return values neverthless.

Replace:
printf("\n\nFor new student, select 1, to exit select 2: ");
     scanf("%d", &prompt);

with

printf ...
i_rval = scanf("%d", &prompt);
if (i_rval != 1) {

}

Regards
Friedrich
0
 
Kent OlsenConnect With a Mentor Data Warehouse Architect / DBACommented:
Hi Susan,  :)

Another small suggestion that will improve the readability of your code and make is slightly smaller is to slightly modify the way that you control the loop.  Friedrich has touched on it.

  int KeepLooping = 1;

  while (KeepLooping)
  {
     //  main  portion of the code

    printf("\n\nFor new student, select 1, to exit select 2: ");
    fflush (stdin);
    while (scanf ("%d", &KeepLooping) ==0);  //repeat the scanf until an integer is entered
  }

This way you decode into the variable that controls the loop.


scanf() does not remove the new-line character from the input stream with the format string of "%d".  The next time that scanf() is called the function "sees" the new-line character is still in the buffer and treats the entire string as if new-line were entered with no data.  However, the scanf() still will not have removed the new-line so you could easily wind up in an infinite loop.

Note the fflush(stdin).  You need to do this before every call to scanf().  (It's optional before the first call.)  That will remove the new-line character.

Good Luck!
Kent
0
 
Cabochick05Author Commented:
Now I am feeling very new...What does the 'i_rval = scanf' do differently than 'scanf' in your code below?

printf ...
i_rval = scanf("%d", &prompt);
if (i_rval != 1) {

}
0
 
Kent OlsenConnect With a Mentor Data Warehouse Architect / DBACommented:

Hi Susan,

scanf() returns the number of items that have been decoded and stored.  For the scanf() statement used here, if scanf() returns a 0, the user entered a new-line (blank line) or other non-digit as the first character.  If the first character is numeric scanf() will return a 1.


Kent

0
 
Cabochick05Author Commented:
Thanks Ken,
I am understanding much more about scanf()!  That it is important to keep it tidy and that friedrich's and your examples are similar in accomplishing the same thing.  I will note your suggestions for my upcoming programming classes and bring this up to my instructor this evening in class.  I am gun-shy to add it into my code for a grade however, as my instructor tends to scream if we do something outside of what he has covered in the classroom...Which leaves little room for creativity and as I've seen so far, proper coding...Thanks so much for making scanf() much more understandable!!
Kindest Regards,
Susan
0
 
fridomCEO/ProgrammerCommented:
Kent please do not post code which is undefined.
fflush(stdin) is not what you want it's fflush(stdout)
fflush is not defined for input streams for that I suggested to use  combination
from fgets + sscanf.


Regards
Friedrich




0
 
Kent OlsenData Warehouse Architect / DBACommented:

Hi Friedrich,

You might want to check out this link:  http://www.cppreference.com/stdio/fflush.html


Kent
0
 
PaulCaswellConnect With a Mentor Commented:
Hi Susan,

Just a small comment/question.

>>        if (gpa >= 0 && gpa <=5)
a) Why is this here? You are effectively checking the entered value with the switch statement.
b) Why 5 when your range is 0-4?

And a small concern.

Is there more information in the question about what 'GPA' stands for? If the 'A' stands for 'Average' then the '20 students' makes a little more sense but you have a little more work to do.

Paul
0
 
Cabochick05Author Commented:
Good catch.  I meant to change to range from 0-4.  I've tried to move the if statement but it always errors out when I do.  Does it go above or below what you are putting the if condition on?
Thanks,
Susan
0
 
fridomCEO/ProgrammerCommented:
To Kent the given page is wrong. The standard is the definitive guide and we are talking about C here so here is the stuff from the ANSI C99 standard.

7.19.5.2

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

Whatever the C++ standard says about this, it has nothing to do with C.

Regards
Friedrich
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Hi Friedrich,

After much searching around the different C support pages I find that you're correct in that the C99 standard says that the behavior is undefined.  I also leared that many/most C implementations now support fflush() on the input stream.

The most notable exception that I found is BSD, where a quick look at the source code revealed that it ignores input streams.  (Then again, I've not used BSD very much.)  :)  I do know that I've used the technique for quite a while without issue.


So indeed you are correct that it's not the standard.  But do note that it is now a common practice.  I suspect that it will become even more so, except perhaps by the "purists" like the folks at BSD.  :)

Kent


Officially, one should probably control the reading of the line with the format string, or execute a small getc() loop to advance past the new-line.
0
 
Cabochick05Author Commented:
Thanks all, I'm going home to make changes and send in to my instructor now.  Class is tonight!  You all have been wonderful.  I truly am relieved since you have all helped me this week. I'm sure I'll be on later tonight stressing about next week's assignement, one of which I know will add to the currency exchange and I believe the enhancement will be to allow exhange from one currency to another at the users choice...I can't even fathom how to do that yet!  Thanks for the help with the fflush() and scanf().  I am going to bring it up tonight. =)
Susan
0
 
Cabochick05Author Commented:
Thanks for the reminder Paul,
I have finished my class and planned to come back and tie up any open questions I have.
Believe it or not I got an A1 in the class when I thought for sure I was going to fail.  
Thanks for all your support.  It has been well worth it and I'm sure I'll be chatting with you during my next programming class!
Kindest Regards,
Susan from PHX
0
 
PaulCaswellCommented:
Susan,

I think I need one little bit of extra help here. If I unaccept this question would you have a go at splitting the points? I think that would be fairer.

It's a little more complicated than just accepting one answer but its much fairer to all the experts who helped out here. Take a look at the help pages to find out how. If you can't get it to work, let me know how you want it split and I can do it for you but with a A1 I'd reckon your quite capable. :-)

Paul <Page Editor>
0
 
Cabochick05Author Commented:
I would be happy to!
Would it be ok if it takes me a few days as I'm almost done here at work then I'll try to get to it this weekend?

SJ
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.