We help IT Professionals succeed at work.

GPA Comments using Switch/Case in Basic C

Cabochick05
Cabochick05 asked
on
1,004 Views
Last Modified: 2012-05-05
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*/
Comment
Watch Question

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
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
fridomCEO/Programmer
CERTIFIED EXPERT

Commented:
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



Author

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

Author

Commented:
Thank you Siddhesh, your comment was very helpful.
Friedrich, I just noticed I mispelled your name earlier, fogive my oversight!
Susan
fridomCEO/Programmer
CERTIFIED EXPERT

Commented:
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
Kent OlsenData Warehouse / Database Architect
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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) {

}
Kent OlsenData Warehouse / Database Architect
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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
fridomCEO/Programmer
CERTIFIED EXPERT

Commented:
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




Kent OlsenData Warehouse / Database Architect
CERTIFIED EXPERT

Commented:

Hi Friedrich,

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


Kent
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

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
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
fridomCEO/Programmer
CERTIFIED EXPERT

Commented:
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
Kent OlsenData Warehouse / Database Architect
CERTIFIED EXPERT

Commented:

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.

Author

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

Author

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
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>

Author

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

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.