Click here to Skip to main content
16,004,678 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have written the following code to the exercise question given at the end of the book from which I'm learning C#.. However, my code gives me an error and I'm not able to find the reason. Can someone please review the code and mention the problem area

///summary
            ///Write a program, which creates an array containing all Latin letters.
            ///The user inputs a word from the console and as result the program
            ///prints to the console the indices of the characters matching array
            static void Main()
            {
            char ch = 'A';
            char[] alph = new char[26];
            for (int row = 0; row < 26; row++)
            {
                alph[row] = ch;
                ch++;
            }
            for (int row = 0; row < 26; row++)
            {
                Console.Write(alph[row] + " ");
            }
            Console.WriteLine();
            Console.Write("Enter word: ");
            string word = Console.ReadLine();
            string wordUpper = word.ToUpper();
            int wrdIdx = 0;
            for (int i = 0; true; i++)
            {
                if (wordUpper[wrdIdx] == alph[i]) //If below if is removed then this gives as error. Same error of overflow
                {
                    Console.Write(i + " ");
                    wrdIdx++;
                    i = 0;
                    if (wordUpper[wrdIdx] == wordUpper.Length - 1) //This line is giving error if i remove it then the error shows above in the IF statement.
                        break;
                }
            }
            }



This is the output and error message that I get:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Enter word: Mohit
12 14 7 8 19
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.String.get_Chars(Int32 index)
   at Revision.Program.Main(String[] args) in C:\Users\mohit\source\Revision\Revision\Program.cs:line 632


What I have tried:

Tried to debug the code. But as I'm a beginner so not able to understand whats going on in the debugger.

I request to please provide a very basic answer without using anything external from what I have written. As i dont know much about other functionalities provided by the various classes and methods. Please try to correct only the current code.

Please also excuse me for my English.

Thanks in advance.
Posted
Updated 11-Oct-18 5:22am

if (wordUpper[wrdIdx] == wordUpper.Length - 1)

wordUpper[wrdIdx] returns a char representing the character at the specified index.

wordUpper.Length - 1 returns an int - a number one less than the length of the string.

In order to compare them, the char will be converted to its Unicode code-point. (Since you're only working with non-accented letters, this is the same as its ASCII[^] value.)

Given the upper-case input string "MOHIT", the numeric value of wordUpper[wrdIdx] will be: 77, 79, 72, 73 and 84. Obviously, none of those values are equal to wordUpper.Length - 1, so your loop never terminates. Once wrdIdx moves past the end of your string, you get the IndexOutOfRangeException when you try to access the next character.

One simple fix would be to use a nested loop:
C#
foreach (char c in wordUpper)
{
    for (int i = 0; i < alph.Length; i++)
    {
        if (c == alph[i])
        {
            Console.Write(i + " ");
            break;
        }
    }
}
 
Share this answer
 
Comments
Mohit Tomar 13-Oct-18 0:43am    
Ooohh Okay... finally I understand now why my code was not working. So I was comparing char codes with int num values, and the system was converting chars to num representation as per ASCII and that's why it was not working. Hmmmm... alright... Thanks for your help .. I really appreciate it. And it is working now... Above all, I learned something new and that is priceless. :-)
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.String.get_Chars(Int32 index)

That isn't a "overflow exception" - it's an "array index exception"which is different.
What it's saying is that i is greater that 25, or wrdIdx exceeds the word length. Why? because your loop is only exited if everything matches and it reaches the break statement.
We can't run your code under the same conditions you do, so it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 
Comments
Mohit Tomar 10-Oct-18 3:53am    
Is there any beginner friendly Debugging tutorial that I can refer to?? Actually, its been only one month since I started with C# so my knowledge is very very limited.
OriginalGriff 10-Oct-18 4:01am    
Loads, and loads:
https://www.google.co.uk/search?q=visual+studio+debugger&oq=visual+studio+debugger&aqs=chrome..69i57j0l5.6712j0j7&sourceid=chrome&ie=UTF-8
Here is the MS one:
https://tutorials.visualstudio.com/vs-get-started/debugging
Mohit Tomar 11-Oct-18 7:18am    
However I was wondering, shouldn't the loop break when it reaches at -----if (wordUpper[wrdIdx] == wordUpper.Length - 1) ----- because at this time the value of both the wordUpper[wrdIdx] and wordUpper.Length - 1 becomes same.
OriginalGriff 11-Oct-18 7:29am    
Yes but that's nested inside another if, so both conditions have to be true. So unless the first condition matches then there is a good possibility of just running on and on until you get an array index problem.
Relying on your data to be valid every time is a dangerous route...
Mohit Tomar 13-Oct-18 0:23am    
Thanks.. :-)
An error message: System.IndexOutOfRangeException: Index was outside the bounds of the array is corelated with an array. An array index starts from zero to the count of elements minus 1. So, the first element in array has an index 0, second - 1, third - 2, ... tenth - 9, etc.

Look at your for loops to resolve your issue.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900