0

My code suppos to print an array of integers in wich the user enters as many elements he wants and enter -99 (as a string) to exit the loop.Also valid entries range is 0 - 10 with 0 and 10 included.I get wrong results when printing the array tha it prints the last entry only and zeros after .The code is in Console C#.Any help will be appreciated.Thanks.

namespace ExeNo1Ch7
{
class Program
{
    static void Main(string[] args)
    {
        int numOfEntry;
        int[] intNumbers = new int[100];

        numOfEntry = GetArrayOfIntegers(intNumbers);
        Console.WriteLine("\t\n You have entered  " + numOfEntry + " values " + "\t\n" + "They are:");
        for (int i = 0; i < numOfEntry; i++)
        {
            Console.WriteLine("\t\n" + intNumbers[i]);
        }

        Console.WriteLine("\t\n<< Press any key to Exit >> ");

        Console.ReadKey();
    }


    public static int GetArrayOfIntegers(int[] anArray)
    {
        string strValue;
        int counter = 0;
        Console.Write("\t\n Enter an enteger from 0 - 10 :");
        strValue = Console.ReadLine();

        for (int i = 0; i < anArray.Length; i++)
        {
            while (strValue != "-99")
            {
                anArray[i] = int.Parse(strValue);
                counter = counter + 1;
                if (anArray[i] >= 0 && anArray[i] <= 10)
                {
                    Console.Write("\t\n Enter an enteger from 0 - 10 :");
                    strValue = Console.ReadLine();                 
                }                 
                else
                {
                    Console.WriteLine("\t\n Please try again entering an integer in the range (0 - 10) only,");
                    Console.Write("\t\n Enter an enteger from 0 - 10 :");
                    strValue = Console.ReadLine();
                }
            }
        }

        return counter;
    }
5
  • The many blank lines in your code make it horrible to read. Commented Dec 19, 2013 at 16:40
  • That's just so very wrong. Your teacher is not going to be happy. To answer your question, the reason you're only printing the last item is because you don't actually increase i at all - all your "spinning" is done in the while cycle inside, so you only assign to the first index, and when you finally input -99 it does the remaining 99 steps (without reading any ints) and returns. Commented Dec 19, 2013 at 16:40
  • 1
    You should not be using a for loop and a while loop. Drop the for loop and keep track of which entries in the array have been filled (via count). Use count to determine where in the array to store the value the user enters. Commented Dec 19, 2013 at 16:42
  • After you get your code working, consider posting it for a code review at codereview.stackexchange.com Commented Dec 19, 2013 at 17:04
  • Actually my c# class teacher doesn't grade any assignments ,not untill the end of the semester and the school admin. doesn't do any thing about it !So yes i'm sort of lost and it's all blamed on the bad school sys :( But thank you so much for grabbing my antention :) Commented Dec 19, 2013 at 17:33

2 Answers 2

2

You have this behavior because you're overwriting the same value over and over in your while loop.

Basically, you have this :

for (i = 0; i < anArray.Length; i++)
{
    while (strValue != "-99")
    {
        anArray[i] = int.Parse(strValue);
    }
}

This means you will loop forever on the same i until the user inputs -99. You should drop the for loop and increment i in the while :

public static int GetArrayOfIntegers(int[] anArray)
{
    string strValue;
    int counter = 0;
    Console.Write("\t\n Enter an enteger from 0 - 10 :");
    strValue = Console.ReadLine();

    int i = 0;
    while (strValue != "-99")
    {
        anArray[i] = int.Parse(strValue);
        counter = counter + 1;
        if (anArray[i] >= 0 && anArray[i] <= 10)
        {
            Console.Write("\t\n Enter an enteger from 0 - 10 :");
            strValue = Console.ReadLine();
        }
        else
        {
            Console.WriteLine("\t\n Please try again entering an integer in the range (0 - 10) only,");
            Console.Write("\t\n Enter an enteger from 0 - 10 :");
            strValue = Console.ReadLine();
        }
        i++;
    }

There's a second problem; you assign the value before the range comparison. You should move the assignation and counter increment into the if block, like this :

public static int GetArrayOfIntegers(int[] anArray)
{
    string strValue;
    int counter = 0;

    Console.Write("\t\n Enter an enteger from 0 - 10 :");
    strValue = Console.ReadLine();
    while (strValue != "-99")
    {
        int value = int.Parse(strValue);
        if (value >= 0 && value <= 10)
        {
            anArray[counter] = value;
            counter = counter + 1;
            Console.Write("\t\n Enter an enteger from 0 - 10 :");
            strValue = Console.ReadLine();
        }
        else
        {
            Console.WriteLine("\t\n Please try again entering an integer in the range (0 - 10) only,");
            Console.Write("\t\n Enter an enteger from 0 - 10 :");
            strValue = Console.ReadLine();
        }
    }
    return counter;
}
Sign up to request clarification or add additional context in comments.

4 Comments

You should add both counter++ and i++ inside of the validation check (if (anArray[i] >= 0 && anArray[i] <= 10)). And you don't need to keep both i and counter anyway - they suddenly mean the same thing :)
The second part is wrong - now you're not validating the number at all, just zero every time. The assignment has to be done before the validation check.
@Luaan Derp, you're right. I'll edit it quickly :P Fixx'd, looks like I went too fast on the second part, thanks!
This code workeed better ! It solved the range issue .Thanks so much for your help :)
0

What you have is a for loop going through the input, but inside of that you also have a while loop going through the input, which is very awkward, and it looks like it would result in you being able to enter that -99 number 100 times.

instead of using both a for loop and a while loop, just && the clauses together in the for loop

    for (int i = 0; i < anArray.Length && strValue != "-99"; i++)
    {

you also should place a strValue = Console.ReadLine(); at the end of your for loop

3 Comments

This will fail if you enter a number outside of the 0-10 range (i gets incremented when it shouldn't). EDIT: And no, -99 is ignored altogether, so it will not be put into the array. But yeah, it will needlessly iterate the for loop and just skip each iteration except for the first one.
@Luaan you wouldn't enforce the 0-10 restriction inside the signature of the for loop in the first place.
@SamIam I wouldn't use a for loop in the first place, it isn't well suited to reading an unknown set of user inputs. And I don't like having more than one condition in a for loop if it doesn't make sense. For is (semanticaly) mainly an iterator, not just a while loop with slightly different syntax :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.