Averages and Grades

Sections3
  1. Code
  2. Control Flow
  3. For loop

Code§

// This function returns a letter grade based on the average of a student
char gradeFunction(double avg) {
  if (avg >= 90) return 'A';
  else if (avg >= 80) return 'B';
  else if (avg >= 70) return 'C';
  else if (avg >= 60) return 'D';
  else return 'F';
}

int main() {
  int count; // Number of grades the user wants to enter
  double sum = 0, grade; // Sum stores total grades, grade holds each input

  // Ask the user to enter total grades between 1 to 5
  std::print("How many grades (1 to 5)? ");
  auto result = std::scan<int>(stdin, "{}");
  count = result->value();

  // Validate that count is between 1 and 5
  if (count < 1 || count > 5) {
    std::println("Invalid number. You must enter between 1 and 5 grades.");
    return 1;  // Exit
  }

  // Loop to collect each grade
  for (int i = 1; i <= count; i++) {
    std::print("Enter grade {}: ", i);
    auto result = std::scan<double>(stdin, {});
    grade = result->value();
    sum += grade;
  }

  // Calculate the average score
  double avg = sum / count;

  // Display numeric average
  std::println("Average: {}", avg);

  // Display letter grade
  std::println("Letter grade: {}", gradeFunction(avg));

Control Flow§

For loop§

This is the last piece of the puzzle for the basic of c++. And we will start moving on to move advance computer science concept and then alternate between c++ and cs

We already know a while loop

int i = 0;
while (i < 10)
{
  doSomething();
  i = i + 1;
}

This is a common pattern that you should know exist, because it is so common that we have a new syntax for it, called the for loop. With the exact same flow, we write

for (int i = 0; i < 10; i = i + 1)
{
  doSomething();
}

Technically, this is just a pattern. Which means, we can do different things in there.

int i = 100;
char c = 'c'
for (i / 10; c == 'a'; c = 'a')
{
  doSomething();
}

// Will be excatly same as below

int i = 100;
char c = 'c';
i / 10;
while (c == 'a')
{
  doSomething();
  c = 'a'
}

If you find the code above makes no logical sense, that is because it is true, I made up the example ( which is compilable ) to show the technicality of for loop, which really is just a shorthand for a specific pattern of the while loop

Discussion

no comments
Commenting as a guest — sign in to comment as yourself.

No comments yet — yours could open the discussion.