Home > Software engineering >  For loop repeating endlessly in C
For loop repeating endlessly in C

Time:10-04

From everything I have looked at I cannot seem to find any problem with my code.

int main()
{   
double honorpoints,totalhp = 0,totalcredits = 0;
int crpassed=0,clpassed = 0, count;
float GPA,credits;
char classx,grade;
printf("How many classes did you take in the semester: ");
scanf("%d", &count);
for(int i = 0; i < count; i  )
{ 
    printf("Enter a Class: \n");
    scanf("%s", &classx);
    printf("Enter the number of credits: ");
    scanf("%f",&credits);
    totalcredits = totalcredits   credits;
    printf("Enter your grade: ");
    scanf("%s",&grade);
    if (grade == 'A')
    {
       honorpoints = credits * 4;
       crpassed = crpassed   credits;
       clpassed = clpassed   1;
    }
    else if (grade == 'B')
    {
       honorpoints = 3 * credits;
       crpassed = crpassed   credits;
       clpassed = clpassed   1;
    }
    else if (grade == 'C')
    {
       honorpoints = 2 * credits;
       crpassed = crpassed   credits;
       clpassed = clpassed   1;
    }
    else if (grade == 'D')
    {
       honorpoints = 1 * credits;
       crpassed = crpassed   credits;
       clpassed = clpassed   1;
    }
    else
       honorpoints=0;
    totalhp = totalhp   honorpoints;
}

When asking for classes it just continues over and over again. it does run through everything in the loop but it does not stop when 'count' is reached it just continuously asks for classes and grades. I am relatively new to working with C so forgive me if this is an obvious syntax error or something but even while looking through other threads I cannot find a problem with mine.

CodePudding user response:

Some of the scanf calls are corrupting memory, resulting in undefined behavior. classx and grade are both single characters:

char classx,grade;

So the following scanf calls won't work properly:

scanf("%s", &classx);
scanf("%s", &grade);

If these values are meant to be single characters, you can use %c as the scanf format. Otherwise, if you want to read strings, then you need to declare them as arrays, and pass them without taking their address. In that case, don't forget to add a character for the terminating null character.

In either case, you may want to change the format strings so that they consume whitespace (you can prefix the format string with a space to achieve that).

  • Related