Nirdoc
Nirdoc

Reputation: 11

I am trying to make this loop work, but I can't

I am trying to make a program to show me the biggest number from input integers from the user and I just really don't understand why it doesn't work.

public class Program
{
    public static void Main()
    {
        int i  = 0;
        int rep = int.Parse(Console.ReadLine());
        int hi = int.Parse(Console.ReadLine());
        int big = 0;
        for( i = 0; i < rep; i++)
        {
            if(hi > big)
            {
                big = hi;
            }

        }
        Console.WriteLine(big);
    }
}

Upvotes: 1

Views: 74

Answers (2)

HungryCoder
HungryCoder

Reputation: 109

I modified as your console.writeline was out of loop. BUT

public class Program
{
public static void Main()
{
    int i  = 0;
    int rep = int.Parse(Console.ReadLine());
    int hi = int.Parse(Console.ReadLine());
    int big = 0;
    for( i = 0; i < rep; i++)
    {
        if(hi > big)
        {
            big = hi;
            Console.WriteLine(big);
        }

    }

}
}

BUT This code is assigning value of hi to big in first loop. Then enters in the 2nd loop and now it wont satisfy if(hi > big) condition as hi and big are now equal. And it will simply end of loop.

Upvotes: 0

Marko Papic
Marko Papic

Reputation: 1926

If you expect user to enter rep number of integers and then find the largest one, then this might work for you:

public class Program
{
    public static void Main()
    {
        int rep = int.Parse(Console.ReadLine());
        int big = 0;
        for(int i = 0; i < rep; i++)
        {
            int hi = int.Parse(Console.ReadLine());
            if(hi > big)
            {
                big = hi;
            }

        }
        Console.WriteLine(big);
    }
}

Assuming your inputs are natural numbers. Otherwise, you might want to replace

int big = 0;

with

int big = int.MinValue;

Upvotes: 1

Related Questions