Halis297
Halis297

Reputation: 21

school homework - grade calculation

i have got questions. my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?

        int not;
        bool test = true;
        for (int i = 0; i < 20; i++)
        {
            Console.Write((i + 1) + (".Not:"));
            not = Convert.ToInt32(Console.ReadLine());

            if (not < 0 || not > 100)
            {
                test = false;
                Console.Write("Try again!");
            }
            else
            {
                test = true;
            }
        }

I want to use bool while doing this. would be glad if you help. thank you in advance

i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?

int not;
        int temp = 0;

        for (int i = 0; i < 20; i++)
        {
            Console.Write("Add Not : ");

            backtoAdd:
            not = Convert.ToInt32(Console.ReadLine());

            if (not < 0 || not > 100)
            {
                Console.WriteLine("Try Again!");
                goto backtoAdd;
            }
            Console.WriteLine((i+1)+". Not : "+not);
            temp = temp + not;
        }
        Console.Write("sum of not : "+temp);
        Console.ReadKey();

Upvotes: -1

Views: 92

Answers (1)

Maytham Fahmi
Maytham Fahmi

Reputation: 33427

As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:

// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;

// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
    // we give input
    string? input = Console.ReadLine();
    // we try to parse our input
    var parsed = int.TryParse(input, out var grade);
    // if our input is parsed correctly
    if (parsed)
    {
        // we check if the input value between the given range
        if (grade < lowestGrade || grade > highestGrade)
        {
            Console.WriteLine("Try Again!");
        }
        else
        {
            // if with in range count
            counter++;
        }
    }
}

Upvotes: 1

Related Questions