Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Translating Pseudocode to JavaScript Code!
You have completed Translating Pseudocode to JavaScript Code!
Preview
Follow along as we translate pseudocode to functioning JavaScript code.
Finished working code
// function calculate_gpa
// pass in student_grades
function calculate_gpa(student_grades) {
// set grade_total to 0
let grade_total = 0;
// for each grade in student_grades
let num_of_grades = student_grades.length;
for (let i = 0; i<num_of_grades; i++) {
let grade = student_grades[i];
// if grade is not a 1, 2, 3, or 4
if (grade < 1 || grade > 4) {
// print "invalid grade" with grade
console.log("invalid grade: " + grade);
// exit function with "can't complete calculation" message
return "Can't complete calculation";
} else {
// else add grade to grade_total
grade_total += student_grades[i];
}
}
// set gpa to grade_total / number of grades
const gpa = grade_total / num_of_grades;
// return gpa
return gpa;
// end function
}
// set reggie_grades to 4, 4, 3, 4
let reggie_grades = [4,4,3,4];
// print the results of calling calculate_gpa with reggie_grades
console.log(calculate_gpa(reggie_grades));
// set dave_grades to 1, 2, 3, 2
let dave_grades = [1,2,3,2]
// print the results of calling calculate_gpa with dave_grades
console.log(calculate_gpa(dave_grades));
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
[MUSIC]
0:00
Hopefully you tried to solve
this challenge yourself,
0:00
based on the previous
step in this workshop.
0:03
If not, you can follow along with me.
0:05
I'll translate this
pseudocode into working code.
0:07
I'll use JavaScript in this example.
0:10
But pseudocode is simply
the outline of a program steps.
0:12
So it can be translated to
any programming language.
0:15
Open the workspace associated with
this video in the gpa.js file.
0:19
This is a JavaScript file, and
0:24
you'll notice that it has the pseudo
code added as code comments.
0:25
First, I'll create the function
structure with opening function name,
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up