Close
Close

im getting error as array out of index could anyone please help

   Randy

Programming language-c#

input-a3b4

output-aaabbb

program

bool result;
            Console.WriteLine("enter the string");
            string a=Console.ReadLine();
            char[] b = a.ToCharArray() ;
            for(int i=0;i<=b.Length;i++)
            {
                result = char.IsLetter(b[i]);
                
                if (result == true)
                {
                    char c = b[i];
                    int count = 0;
                    for (int j = i + 1; j <= b.Length; j++)
                    {

                        if (b[j] >= 0 && b[j] <= 9)
                        {
                            count = (count * 10) + b[j];
                        }
                    }
                    for (int k = 0; i <= count; k++)
                    {
                        Console.Write(c);
                    }

                }
              
            }

 


Answers

  •   

    You need to make the following changes in your code.

    • In the first two for loops, change the conditions to i<b.Length and j<b.Length because the array b is of length 4 with its first and last elements as b[0] and b[3] respectively.
    • In the last for loop, change the condition to k<count
    • In the second for loop, b[j] is of type char. Therefore, you first need to convert it to type int for comparing it with integers and using it in arithematic operations. You can do so by typing (int)Char.GetNumericValue(b[j]).

    The problem statement for your program is not clear but the program runs fine on doing the above changes. I am writing the program again with the changes included.

    using System;
    
    public class Test
    {
    	public static void Main()
    	{
    		bool result;
    		Console.WriteLine("enter the string");
    		string a=Console.ReadLine();
    		char[] b = a.ToCharArray() ;
    		for(int i=0;i<b.Length;i++)
    		{
    			result = char.IsLetter(b[i]);
    			if (result == true)
    			{
    				char c = b[i];
    				int count = 0;
    				for (int j = i + 1; j < b.Length; j++)
    				{
    					if ((int)Char.GetNumericValue(b[j]) >= 0 && (int)Char.GetNumericValue(b[j]) <= 9)
    					{
    						int d = (int)Char.GetNumericValue(b[j]);
    						count = (count * 10) + d;
    					}
    				}
    				for (int k = 0; k < count; k++)
    				{
    					Console.Write(c);
    				}
    			}
    		}
    	}
    }
    

    You can state your problem statement as well if you want to get the correct output.


    • thank you,.,.,
      - Randy
    • could you please help me logic if i/p= a2b2 the above code print "a" 22 time, it cant able to find alphabet "B"
      - Randy
    • Does your problem statement say that the input a2b2 should print aabb and a3b4 should print aaabbbb?
      - Aakhya Singh

Ask Yours
Post Yours
Write your answer