Home > Enterprise >  I am new to programming and C#, I am getting the wrong output for school homework
I am new to programming and C#, I am getting the wrong output for school homework

Time:10-21

int grade, counter = 0;
Console.Write("Please enter a grade");
grade = int.Parse(Console.ReadLine());
if (grade >= 60 && grade != 101)
{
    counter  ;
}
while (grade != 101)
{
    if (grade >= 60 && grade != 101)
    {
        counter  ;
    }
    Console.WriteLine("Please enter another grade, if you no longer wish to enter grades, enter '101' ");
    grade = int.Parse(Console.ReadLine());
}
Console.WriteLine("There are "   counter   " grades that are over 60");

This calculates how many of the grades that are received are over 60, I use a counter to display and count them and to tell the program to finish, you input '101'

Why does the input : 90 1 101 result in the counter being equal to 2?

CodePudding user response:

See comments:

grade = int.Parse(Console.ReadLine());
if (grade >= 60 && grade != 101) // You check first input and ...
{
    counter  ; // increment counter (to 1 because it was 90), then
}
while (grade != 101) // this is true ...
{
    if (grade >= 60 && grade != 101) // you check the >>first input<< _again_ ...
    {
        counter  ;  // and increment counter a second time!
    }
    Console.WriteLine("Please enter another grade, if you no longer wish to enter grades, enter '101' ");
    grade = int.Parse(Console.ReadLine());
}
Console.WriteLine("There are "   counter   " grades that are over 60");

What you would usually do is using a loop that checks the condition after its body (do..while) or make the first check pass. Either way, you'd want to get input once and at the beginning inside the loop.

A little something like this:

// It's considered cleaner to have each var declared in its respective line:
int grade = 0;
int counter = 0;
do
{
    Console.WriteLine("Please enter grade, if you no longer wish to enter grades, enter '101' ");
    if(int.TryParse( Console.ReadLine(), out grade )) // << never "trust" user input!
    {
        if (grade >= 60 && grade != 101)
        {
            counter  ;
        }
    }
    else
    {
         Console.WriteLine("Please enter integer numbers, only! ('101' to exit.)");
    }
}
while( grade != 101 );

Console.WriteLine("There are "   counter   " grades that are over 60");
// While it doesn't make much of a difference _in this case_, you may also consider these alternatives:
// Console.WriteLine("There are {0} grades that are over 60", counter);
// Console.WriteLine($"There are {counter} grades that are over 60");

  •  Tags:  
  • c#
  • Related