In this video lesson we show how to create a program that will input a list of grades, sort them into descending order, average them, and then find the high and low grades. This is a classic first year college programming assignment. We take you through it step by step. For you convenience, we include the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | float grades[25]; int numGrades; int i; String myPrompt; float tmp; int j; int flag = 1; float bucket; float avg; float highGrade = 0; float lowGrade = 100; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.println("How Many Grades? "); while (Serial.available() == 0) { } numGrades = Serial.parseInt(); for (i = 0; i < numGrades; i = i + 1) { myPrompt = "Please Input Grade: " + String(i + 1); Serial.println(myPrompt); while (Serial.available() == 0) { } grades[i] = Serial.parseFloat(); } // for (j = 0; j < numGrades - 1; j = j + 1) { // for (i = 0; i < numGrades - 1 - j; i = i + 1) { // if (grades[i] < grades[i + 1]) { // tmp = grades[i]; // grades[i] = grades[i + 1]; // grades[i + 1] = tmp; // } // } flag=1; while (flag == 1) { flag = 0; for (i = 0; i < numGrades - 1; i = i + 1) { if (grades[i] < grades[i + 1]) { tmp = grades[i]; grades[i] = grades[i + 1]; grades[i + 1] = tmp; flag = 1; } } } Serial.println(); Serial.println("Your Grades Are: "); for (i = 0; i < numGrades; i = i + 1) { Serial.println(grades[i]); } bucket = 0; for (i = 0; i < numGrades; i = i + 1) { bucket = bucket + grades[i]; } avg = bucket / numGrades; Serial.println("Your Average is: " + String(avg)); highGrade = 0; lowGrade = 100; for (i = 0; i < numGrades; i = i + 1) { if (grades[i] > highGrade) { highGrade = grades[i]; } if (grades[i] < lowGrade) { lowGrade = grades[i]; } } Serial.println("Your High Grade is: " + String(highGrade)); Serial.println("Your Low Grade is: " + String(lowGrade)); Serial.println(); } |