CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
if else question

 



adiolord
Novice

Jun 15, 2010, 11:03 AM

Post #1 of 4 (471 views)
if else question Can't Post

Hello all, I would like to know how to write a simple program that asks for your grade (1-100) and gives back a F,D,C,B, or A depending on the grade.

I am fine with getting all the variables, but am stuck on the output.

I have something along these lines to start but am stuck at elsif or else to go through the rest of the grades:

if ( $finalmark < 49 ) {
print "Your grade is F\n";


Zhris
Enthusiast

Jun 15, 2010, 1:45 PM

Post #2 of 4 (457 views)
Re: [adiolord] if else question [In reply to] Can't Post

Hello,

If you want to go the if / elsif / else route, then the following should be fine:


Code
my $finalmark = 60; 

if ($finalmark < 49) {
print "Your grade is F\n";
}
elsif (($finalmark >= 49) && ($finalmark < 59)) {
print "Your grade is E\n";
}
#etc
else {
print "Your grade is A\n";
}


Personally I would use a hash table to provide information about each grade and the score boundaries (this method allows you to change how a grade is allocated by changing the values in the hash table):


Code
my $finalmark = 60; 

my %grades = (
'E' => [0, 20],
'D' => [21, 40],
'C' => [41, 60],
'B' => [61, 80],
'A' => [81, 100]
);

foreach (keys %grades) {
if (($finalmark >= ${$grades{$_}}[0]) && ($finalmark <= ${$grades{$_}}[1])) {
print "Your grade is $_\n";
}
}


Chris


(This post was edited by Zhris on Jun 19, 2010, 1:19 PM)


BillKSmith
Veteran

Jun 15, 2010, 1:58 PM

Post #3 of 4 (451 views)
Re: [Zhris] if else question [In reply to] Can't Post


Code
  

my $grade = $final_mark > 90 ? 'A'
: $final_mark > 80 ? 'B'
: $final_mark > 70 ? 'C'
: $final_mark > 65 ? 'D'
: 'F'
;

Good Luck,
Bill


Zhris
Enthusiast

Jun 15, 2010, 2:02 PM

Post #4 of 4 (450 views)
Re: [BillKSmith] if else question [In reply to] Can't Post

Ah, thats good!

Chris

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives