Search code examples
cinfinite-loop

'For' loop in C loops endlessly


I know this has been asked before, but I've been unable to find an answer I can apply to my case.

I've been unable to get this For loop to end. I'm sure it's something simple, can anyone tell me what i'm doing wrong?

#include <stdio.h>
int main ()
{
  /* variable definition: */
  char StudentName[100];
  float ExamValue, Sum, Avg;
  int students, exams;
  int Total_Students;

    printf("Enter total number of students: \n");
    scanf("%d", &Total_Students);

   // Loop through x students
  for (students = Total_Students; students++;)
  {
     // reset Sum to 0
     Sum =0.0;  
     printf("Enter Student Name \n");
     scanf("%s", StudentName); 

     // Nested Loop for Exams
    for (exams=0; exams < 3; exams++)
    {
        printf ("Enter exam grade: \n");
        scanf("%f", &ExamValue);
        Sum += ExamValue;
    }   
    Avg = Sum/3.0;
    printf( "Average for %s is %f\n",StudentName,Avg);
  }
  return 0;
}

Solution

  • This code can solve your problem. you should make condition like this, set the start, end point accurately

    #include <stdio.h>
    int main()
    {
    /* variable definition: */
    char StudentName[100];
    float ExamValue, Sum, Avg;
    int students, exams;
    int Total_Students;
    
    printf("Enter total number of students: \n");
    scanf_s("%d", &Total_Students);
    
    // Loop through x students
    // you should make condition like this, set the start, end point accurately
    for ( students = Total_Students; students>0; students--)
    {
        // reset Sum to 0
        Sum = 0.0;
        printf("Enter Student Name : \n");
        scanf_s("%s", StudentName,sizeof(StudentName));
        getchar();
    
        // Nested Loop for Exams
        for (exams = 0; exams < 3; exams++)
        {
            printf("Enter exam grade: \n");
            scanf_s("%f", &ExamValue);
            Sum += ExamValue;
        }
        Avg = Sum / 3.0;
        printf("Average for %s is %f\n", StudentName, Avg);
    }
    return 0;
    }