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.