0

I have this task: Task Given an array of ints, print 'true' if the number of '1's is fewer than the number of '4's.

Input Format The first line contains a single integer, n, denoting the size of the array. The second line contains the integers of the array in corresponding order. The mentioned integers are separated by space characters (' ').

Output Format Simply the word 'True' or 'False'.

Sample Input

2
1 4

Output Format False

And this is my code:

int szam = Convert.ToInt32(Console.ReadLine());
int[] szamok = new int[szam];
int szam1 = 0;
int szam4 = 0;


for (int i = 0; i < szamok.Length; i++)
{
    int ertek = Convert.ToInt32(Console.ReadLine());    
    
    szamok[i] = ertek;
}
foreach (int i in szamok)
{
    if (i == 1)
    {
        szam1++;
    }
    if (i == 4)
    {
        szam4++;
    }
}
if (szam4 > szam1 && szam4 != szam1)
{
    Console.WriteLine("True");
}
else
{
    Console.WriteLine("False");
}

This code is work for me right when, i use it in visual studio, but it do not work in the website where i need to put my code because the user input coming with spaces.

explain how the input coming in the website: 1 4 3 1 so when i run it got the "Input string was not in a correct format" error, because of the spaces. How can i read the numbers from the input without spaces? Thx for help.

2
  • You will need to read in the numbers as a single string (e.g. "2 1 4") and split it up by using string.Split() to get an array of strings. Then iterate through the strings in the array and convert each to an integer using Convert.ToInt32() or int.Parse(). Then add each parsed integer to the int array. Hopefully that should be enough to get you going - I'm not going to post any code because this is (I assume) supposed to be a learning excercise. Commented Oct 12, 2022 at 9:19
  • This was my first question in this page and you writes the solution so fast what is solved my problem. I want to say a big thank you for your help sir! I am really thankful for your help. Commented Oct 12, 2022 at 21:06

1 Answer 1

1

You can use string.Split:

string[] input = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);
int[] numbers = Array.ConvertAll(input, int.Parse);

Of course it would be better to use int.TryParse because the user can enter invalid integers:

int[] numbers = input
    .Select(s => int.TryParse(s, out int i) ? i : new Nullable<int>())
    .Where(i => i.HasValue)
    .Select(i => i.Value)
    .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

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.