0

I have taken a look at the question asked here : Why does the "for" loop execute one more time than the body of the loop?

But I couldn't understand that. I have just begun learning C on my own. And there is a for loop in a program that I am writing, that is executing 6 times instead of 5, and then its also ignoring the value entered the 6th time. But it still asks the user for the value for the 6th time.

for (int counter = 1; counter <= 5; ++counter)
    {
        scanf_s("%f\n", &mk);
        mk_total += mk;
    }

the variable mk has been initialized to 0 already. Here is the whole program :

#include <stdio.h>
#include <conio.h>

int main()
{
    char name[20];
    float mk = 0; // mk= marks scored out of 100
    float percentage, average, mk_total = 0; // mk_total = total marks
    char grade;

    printf("Enter your name : ");
    gets(name);

    printf("Enter your marks (out of 100) in 5 subjects repsectively :\n");

    for (int counter = 1; counter <= 5; ++counter)
    {
        scanf_s("%f\n", &mk);
        mk_total += mk;
    }

    percentage = (mk_total / 500) * 100;
    average = (mk_total / 5);

    if (average < 50)
        grade = 'F';
    if (average >= 50 && average < 60)
        grade = 'C';
    if (average >= 60 && average < 70)
        grade = 'B';
    if (average >= 70 && average < 80)
        grade = 'B+';
    if (average >= 80 && average < 90)
        grade = 'A';
    if (average >= 90 && average <= 100)
        grade = 'O';

    printf("Name of the Student : %s\n", name);
    printf("Total marks secured : %g\n", mk_total);
    printf("Percentage secured  : %g\n", percentage);
    printf("Grade secured       : %c\n", grade);

    return 0;
}

The output asks the user for input a 6th time even after entering 5 values each separated by the enter/return key on my keyboard. Is there any way to prevent this ? I just used the for loop because I thought it would be cool to add numbers and it would use less variables.

Koustubh Jain
  • 129
  • 1
  • 7
  • 3
    https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – Passerby Jan 25 '22 at 11:10
  • 1
    A trailing `\n` in a `scanf` format string is almost always wrong. See the duplicate post for details. Try with it removed. – kaylum Jan 25 '22 at 11:11
  • 1
    On an unrelated note, if you use `else if` (and reverse the order) you could simplify the grading. As in `if (average >= 90) { grade = 'O'; } else if (average >= 80) { ... } ... else { grade = 'F'; }` – Some programmer dude Jan 25 '22 at 11:16
  • Dividing a floating point value by 500 and multiplying again with 100 is the same as simply dividing by 5 – mathematically always exactly, with floating point potentially some rounding issues come into play, but that's probably neglectable in your case... – Aconcagua Jan 25 '22 at 11:37

0 Answers0