Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Finding smaller number of 2 numbers inputted by user

  • 21-09-2017 2:24pm
    #1
    Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭


    Recently started a C# course, is there a more effective way of finding which int value is the smaller of the two that are inputted by a user? the program works ok but I can't but feel there's a better way of doing it

    3favVik.png


«134

Comments

  • Registered Users, Registered Users 2 Posts: 17,708 ✭✭✭✭Mr. CooL ICE


    Well for a start, you're printing out the variable name rather than the value. I'm not sure if that's intended.

    Also, is this example supposed to take into account num1 and num2 being equal?


  • Registered Users, Registered Users 2 Posts: 1,931 ✭✭✭PrzemoF


    I hope I won't get banned by instructing a mod how to post code :-)
    but it's easier to read it if you post the code with:
    ""
    ""
    
    You have 3 options:
    a>b
    a=b
    a<b
    You can do checks using "if" as you did - that's the obvious choice. You could also  sub a from b 
    [code]c = a - b
    
    and use case switch [1] for the check. Is it better? Probably not :D

    [1] https://en.wikipedia.org/wiki/Switch_statement


  • Registered Users, Registered Users 2 Posts: 1,717 ✭✭✭Raging_Ninja


    You're learning from scratch, looks like the basics of if/else statements, assignment operations and equality tests. Handle the scenario for when the two numbers are equal and you ought to be done.

    Efficiency comes later on, once you've learned enough to be able to understand why an alternative might be more efficient.


  • Registered Users, Registered Users 2 Posts: 6,286 ✭✭✭Talisman


    When starting out keep your code as simple as possible use if-else. As you become more familiar with programming you will discover the ?: ternary operator.
    class SimpleConditional
    {
        static void Main()
        {
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
    
            // simple if-else construction
            if (a < b)
                Console.WriteLine("A is smaller.");
            else
                Console.WriteLine("B is smaller.");
    
            // ?: conditional operator
            Console.WriteLine( (a < b) ? "A is smaller." : "B is smaller." );
        }
    }
    


  • Registered Users, Registered Users 2 Posts: 7,501 ✭✭✭BrokenArrows


    Dont forget to account for when the numbers are equal.
        if(a < b)
            Console.WriteLine("a is smaller");
        else if(b < a)
            Console.WriteLine("b is smaller");
        else
            Console.WriteLine("a & b are equal");
    
    

    As a side note there is a method in the Math class which returns the higher of two numbers but you're better off at the moment writing the necessary code yourself to learn.
        int Higher = Math.Max(100, 200);
    
        // In this case the Higher variable will be set to 200. 
    
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,286 ✭✭✭Talisman


    Dont forget to account for when the numbers are equal.
        if(a < b)
            Console.WriteLine("a is smaller");
        else if(b < a)
            Console.WriteLine("b is smaller");
        else
            Console.WriteLine("a & b are equal");
    
    
    You don't necessarily have to deal with the case of a = b. If the question is "Is a smaller than b?" then there are only two possible answers : Yes (1) or No (0).

    If the answer is "No" then b is smaller or worst case is equal to a. The a equals b check is a special case which you only need to check in the event that you have to handle that scenario. In the scope of the question "Is a smaller than b?" the special case isn't a concern.


  • Registered Users, Registered Users 2 Posts: 7,501 ✭✭✭BrokenArrows


    Talisman wrote: »
    You don't necessarily have to deal with the case of a = b. If the question is "Is a smaller than b?" then there are only two possible answers : Yes (1) or No (0).

    If the answer is "No" then b is smaller or worst case is equal to a. The a equals b check is a special case which you only need to check in the event that you have to handle that scenario. In the scope of the question "Is a smaller than b?" the special case isn't a concern.

    haha.
    The life long problem of a software developer.

    Do you write to the exact specification or do you enhance it to take into account something the spec writer missed :D


  • Registered Users, Registered Users 2 Posts: 6,286 ✭✭✭Talisman


    Do you write to the exact specification or do you enhance it to take into account something the spec writer missed :D
    That's where acceptance tests save your ass.


  • Registered Users, Registered Users 2 Posts: 24,558 ✭✭✭✭lawred2


    Talisman wrote: »
    When starting out keep your code as simple as possible use if-else. As you become more familiar with programming you will discover the ?: ternary operator.
    class SimpleConditional
    {
        static void Main()
        {
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
    
            // simple if-else construction
            if (a < b)
                Console.WriteLine("A is smaller.");
            else
                Console.WriteLine("B is smaller.");
    
            // ?: conditional operator
            Console.WriteLine( (a < b) ? "A is smaller." : "B is smaller." );
        }
    }
    

    I spot a bit of a bug there horse


  • Registered Users, Registered Users 2 Posts: 24,558 ✭✭✭✭lawred2


    Talisman wrote: »
    You don't necessarily have to deal with the case of a = b. If the question is "Is a smaller than b?" then there are only two possible answers : Yes (1) or No (0).

    If the answer is "No" then b is smaller or worst case is equal to a. The a equals b check is a special case which you only need to check in the event that you have to handle that scenario. In the scope of the question "Is a smaller than b?" the special case isn't a concern.

    I think the scope of the OPs question was which of the two is the smaller - ergo you do need to check for them being equal..


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Thanks for all the replies.

    Well for a start, you're printing out the variable name rather than the value. I'm not sure if that's intended.

    Also, is this example supposed to take into account num1 and num2 being equal?


    The full exercise question was

    Prompt the user to enter two int values. your program should find the smaller of the two int values and output the number


    PrzemoF wrote: »
    I hope I won't get banned by instructing a mod how to post code :-)


    No fear of that happening, I'm not a mod of this forum :).

    Talisman wrote: »
    When starting out keep your code as simple as possible use if-else. As you become more familiar with programming you will discover the ?: ternary operator.
    class SimpleConditional
    {
        static void Main()
        {
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
    
            // simple if-else construction
            if (a < b)
                Console.WriteLine("A is smaller.");
            else
                Console.WriteLine("B is smaller.");
    
            // ?: conditional operator
            Console.WriteLine( (a < b) ? "A is smaller." : "B is smaller." );
        }
    }
    

    When we were doing user input the other day he never showed us this int a = Convert.ToInt32(Console.ReadLine()); Is that basically converting a string or char variable too an int?


  • Registered Users, Registered Users 2 Posts: 6,286 ✭✭✭Talisman


    When we were doing user input the other day he never showed us this int a = Convert.ToInt32(Console.ReadLine()); Is that basically converting a string or char variable too an int?
    Yes the Convert.ToInt32(value) method converts a string value to a 32-bit integer. There is also the Int32.Parse(value) method.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    I'll post more code soon for y'all to dissect. :pac:


  • Registered Users, Registered Users 2 Posts: 23,077 ✭✭✭✭Esel
    Not Your Ornery Onager


    Any need to check that the data given are numbers?

    Not your ornery onager



  • Registered Users, Registered Users 2 Posts: 6,286 ✭✭✭Talisman


    I'll post more code soon for y'all to dissect. :pac:
    You should install an offline documentation browser, it will help you discover the features of the language more easily and take a bit of frustration out of the learning process.

    Windows / Linux : Zeal (Open Source)
    Mac OS : Dash (Commercial app)


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Really struggled with the what we were doing today, we were combining if statements with loops and had too for example print out all the even number between 1 and 100 and the same for odd numbers and then print only the numbers that could be divided by 3, then we had too do the same for strings, I thought my head was gonna explode :-/.


  • Registered Users, Registered Users 2 Posts: 24,558 ✭✭✭✭lawred2


    Really struggled with the what we were doing today, we were combining if statements with loops and had too for example print out all the even number between 1 and 100 and the same for odd numbers and then print only the numbers that could be divided by 3, then we had too do the same for strings, I thought my head was gonna explode :-/.

    look up the modulus operator


  • Registered Users, Registered Users 2 Posts: 2,482 ✭✭✭SweetCaliber


    Really struggled with the what we were doing today, we were combining if statements with loops and had too for example print out all the even number between 1 and 100 and the same for odd numbers and then print only the numbers that could be divided by 3, then we had too do the same for strings, I thought my head was gonna explode :-/.

    As said above, modulus would be your best friend for those three tasks.
    int[] numbers = new int[101];
    
    // Populate the array (faster than using Enumerable)
    for (int i = 1; i < 101; i++) {
     numbers[i] = i;
    }
    
    
    // Get even numbers in array.
    Console.WriteLine("List of even numbers: ");
    for (int i = 1; i < numbers.Length; i++) {
    
     // Check if modulus = 0
     if (numbers[i] &#37; 2 == 0) {
      Console.WriteLine(numbers[i]);
     }
    
    }
    
    
    // Get odd numbers in array (same as even except modulus != 0)
    Console.WriteLine("List of odd numbers: ");
    for (int i = 1; i < numbers.Length; i++) {
    
     // Check if modulus = 0
     if (numbers[i] % 2 != 0) {
      Console.WriteLine(numbers[i]);
     }
    
    }
    
    // Get numbers that only divide by 3 (modulus 3 = 0)
    Console.WriteLine("List of numbers divisible by 3: ");
    for (int i = 1; i < numbers.Length; i++) {
    
     // Check if modulus = 0
     if (numbers[i] % 3 == 0) {
      Console.WriteLine(numbers[i]);
     }
    
    }
    
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Thanks lads much appreciated.


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    Really struggled with the what we were doing today, we were combining if statements with loops and had too for example print out all the even number between 1 and 100 and the same for odd numbers and then print only the numbers that could be divided by 3, then we had too do the same for strings, I thought my head was gonna explode :-/.

    I would always recommend keeping it simple - first print out all the numbers, then work out how to print even/odd - if you can attempt this then you will find there are functions which make it easier as you progress, but by then your problem solving will improve as well as your coding...


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 1,931 ✭✭✭PrzemoF


    Really struggled with the what we were doing today, we were combining if statements with loops and had too for example print out all the even number between 1 and 100 and the same for odd numbers and then print only the numbers that could be divided by 3, then we had too do the same for strings, I thought my head was gonna explode :-/.

    That's the feeling of new neurons being formed quickly inside your brain! :-)

    As begbysback wrote: do no try to do it all in one go. Try to split the task.

    Do you draw algorithms as part of the lesson? [1]

    [1] https://en.wikipedia.org/wiki/Algorithm


  • Registered Users, Registered Users 2 Posts: 897 ✭✭✭moycullen14


    Thanks lads much appreciated.

    On the bright side, once you have this done, you'll probably be able for the FIZZ BUZZ test, that apparently most programmers can't do.

    http://wiki.c2.com/?FizzBuzzTest


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    On the bright side, once you have this done, you'll probably be able for the FIZZ BUZZ test, that apparently most programmers can't do.

    http://wiki.c2.com/?FizzBuzzTest

    Was just going to mention this. Fizz Buzz will help in understanding a lot of this


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    PrzemoF wrote: »
    That's the feeling of new neurons being formed quickly inside your brain! :-)

    As begbysback wrote: do no try to do it all in one go. Try to split the task.

    Do you draw algorithms as part of the lesson? [1]

    [1] https://en.wikipedia.org/wiki/Algorithm

    We don't no but I can how helpful that would be and will give it a go.

    We were learning about methods today, i'll post up some code tomorrow.


  • Registered Users, Registered Users 2 Posts: 24,558 ✭✭✭✭lawred2


    Thanks lads much appreciated.

    On the bright side, once you have this done, you'll probably be able for the FIZZ BUZZ test, that apparently most programmers can't do.

    http://wiki.c2.com/?FizzBuzzTest

    Most new programmers


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    At the start, some flow charts may help you to visualise what you are trying to achieve before you write some code. Some people can see this immediately, some can't. Either way its a helpful tool.

    Try to avoid screen shots when posting code, use the code tags, so
    its easier for us to read / copy paste into a dev environment
    
    Makes it easier for us


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    At the start, some flow charts may help you to visualise what you are trying to achieve before you write some code. Some people can see this immediately, some can't. Either way its a helpful tool.

    Try to avoid screen shots when posting code, use the code tags, so
    its easier for us to read / copy paste into a dev environment
    
    Makes it easier for us

    Will do .


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    Probably not ur issue - but u have = 21 twice, so both conditions are true for 21


    Also when using if, best practice is to cover all eventualities - this can be achieved by inserting one more else for greater than last number - just output "too old to drive"


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    How do I pass values from one block of if statments too another ? I know methods would be better for this but wanna try it this way

    namespace ConsoleApplication11
    {
        class Program
        {
            static void Main(string[] args)
            {
               
               double discount1 = 0.05;
               double discount2 = 0.10;
               double discount3 = 0.15;
               double discount4 = 0.20;
                double discount5 = 0.25;
               double additionalCharge = 0.15;
               double additionalCharge2 = 0.10;
               double additionalCharge3 = 0.22;
               int carEngine1 = 2000;
               int carEngine2 = 3000;
               int premium = 800;
               
    
    
               Console.WriteLine("Please enter your Age: ");
                int driverAge = int.Parse(Console.ReadLine());
               
                
                if (driverAge >= 17 && driverAge < 21)
                {
                    Console.WriteLine("Your insurance premium is " + (additionalCharge * premium + premium));
                }
            
                else if (driverAge >=21 && driverAge < 30)
                {
                   Console.WriteLine("Your insurance premium is: " + (additionalCharge2 * premium + premium));
                 }
            
                else if(driverAge >= 30 && driverAge < 80)
                {
                Console.WriteLine("You have no additional charge and your premium is 800.");
                
                }
                else if (driverAge >= 80)
                {
                    Console.WriteLine("Your insurance premium is: " + (additionalCharge3 * premium + premium));
                
                }
    
                Console.WriteLine("Please enter the number of years you have been driving without claiming: ");
                int claim = int.Parse(Console.ReadLine());
    
                if (claim == 1)
                {
                    Console.WriteLine("You get a discount of 5%! " + (premium * discount1));
                    
                }
    
                else if (claim == 2)
                {
                 Console.WriteLine("You get a discount of 10% " + (premium*discount2));
                
                }
    
                else if (claim == 3)
                {
                    Console.WriteLine("You get a discount of 15% " + (premium*discount3));
                
                }
    
                else if (claim == 4)
                {
                    Console.WriteLine("You get a discount of 20% " + (premium*discount4));
    
                }
                else if (claim == 5)
                {
    
                    Console.WriteLine("You get a discount of 25% " + (premium * discount5));
    



    Basically I want the program too remember the choice made up in the first block of if statments and then too be applied too the next block if that makes sense :o .


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    Not quite sure I understand the question. Since everything is in the main method, all variables that are declared are within scope, so the driverage variable that you read in at the top will still be available at the time you are asking for the claims free driving / at the end of the process.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Not quite sure I understand the question. Since everything is in the main method, all variables that are declared are within scope, so the driverage variable that you read in at the top will still be available at the time you are asking for the claims free driving / at the end of the process.

    Sorry what I meant was after the program does the calculation in the first block of ifs depending on what age range you chose, how do you carry that answer down too the next block so it can take 5% discount off or whatever it may be? atm its just giving me one answer for the first block of ifs and then a separate one for the next, if ya get me?


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    Sorry what I meant was after the program does the calculation in the first block of ifs depending on what age range you chose, how do you carry that answer down too the next block so it can take 5% discount off or whatever it may be? atm its just giving me one answer for the first block of ifs and then a separate one for the next, if ya get me?
    If I understand you correctly then, you can assign a value to a variable within the condition, within same curly brackets- so if age == 20 then print "stuff";
    newVar = 48;


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    He gave us another Car insurance exercise where we have too spilt it up in methods, we have too use the same data as the other one I posted, Decided too try and tackle it, below is the age method which is the same as the other one posted, I think it somewhat right, except where you see the ProcessAge in bold it has a red line under and I cant see what I'm doing wrong, if any of ye could have a look and advise I'd be grateful, thanks.

    When I hover over it, it says not all code paths return a value.

    static void Main(string[] args)
            {
                Console.WriteLine(ProcessAge(0.15,0.10,0.22,800,0));
            }
    
            static double [B]ProcessAge[/B](double additionalCharge1, double additionalCharge2, double additionalCharge3,int premium,int age)
            {
                Console.WriteLine("Please enter your age: ");
                int driverAge = int.Parse(Console.ReadLine());
                   
    
                if (driverAge >= 17 && driverAge < 21)
                {
    
                    Console.WriteLine("Your insurance premium is: " + (additionalCharge1 * premium + premium));
                
                }
            
            
            
            }
        
        
        
        
        }
         
    }
    


  • Registered Users, Registered Users 2 Posts: 991 ✭✭✭Greyian


    He gave us another Car insurance exercise where we have too spilt it up in methods, we have too use the same data as the other one I posted, Decided too try and tackle it, below is the age method which is the same as the other one posted, I think it somewhat right, except where you see the ProcessAge in bold it has a red line under and I cant see what I'm doing wrong, if any of ye could have a look and advise I'd be grateful, thanks.

    When I hover over it, it says not all code paths return a value.

    static void Main(string[] args)
            {
                Console.WriteLine(ProcessAge(0.15,0.10,0.22,800,0));
            }
    
            static double [B]ProcessAge[/B](double additionalCharge1, double additionalCharge2, double additionalCharge3,int premium,int age)
            {
                Console.WriteLine("Please enter your age: ");
                int driverAge = int.Parse(Console.ReadLine());
                   
    
                if (driverAge >= 17 && driverAge < 21)
                {
    
                    Console.WriteLine("Your insurance premium is: " + (additionalCharge1 * premium + premium));
                
                }
            
            
            
            }
        
        
        
        
        }
         
    }
    

    The issue with the ProcessAge method is that you have it set up to return a double (static double ProcessAge), but you don't have return any values, you just write to the console.

    Here's an example of how that type of functionality should work:
    static void Main(string[] args)
    {
        int num1 = 1;
        int num2 = 2;
        int sumValue = Sum(num1, num2);
        Console.WriteLine("The sum of " + num1 + " and " + num2 + " is " + sumValue + ".");
    }
    
    static int [B]Sum[/B](int n1, int n2)
    {
        int answer;
        answer = n1+n2;
        return answer;
    }
    

    If your method has a return type (so the double in your ProcessAge example, or the int in my Sum example), you must return a value of that type.

    So just to walk your through how it works:
    • We start in the Main module.
    • We create 2 variables (num1 and num2) and give them values.
    • We then create a 3rd variable (sumValue), and the value of that is the value return from the Sum module.
    • For the Sum module, we require 2 integers as inputs. We are using num1 and num2.
    • So the answer is n1+n2 (or 3).
    • This value is then returned to the main module, and assigned to the sumValue variable.
    • We then write the answer out to the console.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    I was just thinking after maybe it was because I had no return values, thank you.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    I was just thinking after maybe it was because I had no return values, thank you.

    Visual studio will tell you this if you hover over the red line at the time


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    If I wanted too put a loop into the program below, would it go in the main method?
    static void Main(string[] args)
            {
                Console.WriteLine("Please enter a number");
                int value = int.Parse(Console.ReadLine());
    
                TestOddOrEven(value);
    
    
                Console.WriteLine("Please enter a mark between 0 - 100: ");
                int mark = int.Parse(Console.ReadLine());
    
                TestResults(mark);
               
    
    
    
            }
            static void TestOddOrEven(int value)
            {
                if (value % 2 == 0)
                {
    
                    Console.WriteLine("Number is even");
    
                }
                else
                {
                    Console.WriteLine("Number is odd");
                
                }
    
                  return;
            
            
            }
    
    
            static void TestResults(int mark)
        
        
        {
           if(mark <= 100 && mark > 85)
        {
          Console.WriteLine("You got an A!");
        }
    
           else if (mark <= 84 && mark > 70)
           {
               Console.WriteLine("You got a B, well done! ");
           
           }
           else if (mark <= 69 && mark > 55)
           {
               Console.WriteLine("You got a C, Not a bad effort! ");
           }
    
           else if (mark <= 54 && mark > 40)
           {
               Console.WriteLine("You got a D, You can do better than that! ");
           }
           else if (mark <= 39 && mark > 25)
           {
               Console.WriteLine("You got an E....Very Poor grade! ");
           }
           else if (mark <= 24 && mark > 0)
           {
               Console.WriteLine("You get no grade!............very poor result! ");
           
           }
           else if (mark <= 0)
           {
               Console.WriteLine("Error invalid number entered! ");
           }
           else if (mark >= 100)
           {
            Console.WriteLine("Error! invalid amount entered! ");
           }     
                
    
    
            return; 
        }
        
    


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    If I wanted too put a loop into the program below, would it go in the main method?
    static void Main(string[] args)
            {
                Console.WriteLine("Please enter a number");
                int value = int.Parse(Console.ReadLine());
    
                TestOddOrEven(value);
    
    
                Console.WriteLine("Please enter a mark between 0 - 100: ");
                int mark = int.Parse(Console.ReadLine());
    
                TestResults(mark);
               
    
    
    
            }
            static void TestOddOrEven(int value)
            {
                if (value % 2 == 0)
                {
    
                    Console.WriteLine("Number is even");
    
                }
                else
                {
                    Console.WriteLine("Number is odd");
                
                }
    
                  return;
            
            
            }
    
    
            static void TestResults(int mark)
        
        
        {
           if(mark <= 100 && mark > 85)
        {
          Console.WriteLine("You got an A!");
        }
    
           else if (mark <= 84 && mark > 70)
           {
               Console.WriteLine("You got a B, well done! ");
           
           }
           else if (mark <= 69 && mark > 55)
           {
               Console.WriteLine("You got a C, Not a bad effort! ");
           }
    
           else if (mark <= 54 && mark > 40)
           {
               Console.WriteLine("You got a D, You can do better than that! ");
           }
           else if (mark <= 39 && mark > 25)
           {
               Console.WriteLine("You got an E....Very Poor grade! ");
           }
           else if (mark <= 24 && mark > 0)
           {
               Console.WriteLine("You get no grade!............very poor result! ");
           
           }
           else if (mark <= 0)
           {
               Console.WriteLine("Error invalid number entered! ");
           }
           else if (mark >= 100)
           {
            Console.WriteLine("Error! invalid amount entered! ");
           }     
                
    
    
            return; 
        }
        
    

    It really depends on what you want to loop over, and when you want to call the loop......

    can you give some more information?


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    It really depends on what you want to loop over, and when you want to call the loop......

    can you give some more information?

    When the user enters the input I want the program too loop around again and ask for input again for both questions and I want it too do repeatedly.


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    When the user enters the input I want the program too loop around again and ask for input again for both questions and I want it too do repeatedly.

    Something like this?
    Give them the option to quit out that doesn't involve ctrl+c.
    I've used inputting q in the example below.
    static void Main(string[] args)
    {
            while(true)
    	{
    		Console.WriteLine("Please enter a number");
    		string value = Console.ReadLine();
    		if(value.Equals("Q",StringComparison.InvariantCultureIgnoreCase))
    		{
    			break;
    		}
    		TestOddOrEven(int.Parse(value));
    
    
    		Console.WriteLine("Please enter a mark between 0 - 100: ");
                    string mark = Console.ReadLine();
                    if (value.Equals("Q", StringComparison.InvariantCultureIgnoreCase))
                    {
                        break;
                    }
    
    		TestResults(int.Parse(mark));
    	}
    
    }    
    


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    What does break do? Is like the break in a switch statment? never seen it in the context that you wrote it.


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    break exits the parent loop which in this case is the while loop.

    You can also use continue if you want to skip to the next iteration of the loop.

    Break in a switch statement is to prevent you executing the code in the next case.

    They're basically the same.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    When writing methods does it matter if you put public at the start or not? e.g public static void


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    When writing methods does it matter if you put public at the start or not? e.g public static void

    Yes.

    That is an access modifier

    Basically it defines whether other code can access the method.


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    When writing methods does it matter if you put public at the start or not? e.g public static void

    As above yes, it does matter. However, for the stage that you're at in learning the chances are all of your methods will begin with public static


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    As above yes, it does matter. However, for the stage that you're at in learning the chances are all of your methods will begin with public static

    Good point. The modifiers only come into play when your application has multiple classes.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Anyone tell me why this wont print out the "Wrong country entered" when I don't enter in one of the below string variable ? it won't print out the error msg for me at all.
    bool isvalid = false;
                string Country1 = "Ireland";
                string Country2 = "UK";
                string Country3 = "Poland";
    
    
                do
                {
                    try
                    {
    
                        Console.WriteLine("Please enter your Home Country");
                        string country = Console.ReadLine();
    
                        if (Country1 == "Ireland")
                        {
                            Console.WriteLine("Thank you!");
                        }
                        else if (Country2 == "UK")
                        {
                            Console.WriteLine("Thank you");
                        }
                        else if (Country3 == "Poland")
                        {
                            Console.WriteLine("Thank you");
                            isvalid = true;
                        }
    
                        
    
                     
    
    
    
                    }
                    catch (FormatException fe)
                    {
                        Console.WriteLine("Wrong country entered! please try again! ");
                    }
    
    
    
                } while (isvalid == false);
    
            }
        }
    }
    


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    Country 1,2and 3 conditions are true because you have assigned them values - and are testing those values to see if they are true - what you enter on cmd line is not relevant given that you don't assign that value to any of the variables.

    Sry can't help with the code, only logic


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    Anyone tell me why this wont print out the "Wrong country entered" when I don't enter in one of the below string variable ? it won't print out the error msg for me at all.
    bool isvalid = false;
                string Country1 = "Ireland";
                string Country2 = "UK";
                string Country3 = "Poland";
    
    
                do
                {
                    try
                    {
    
                        Console.WriteLine("Please enter your Home Country");
                        string country = Console.ReadLine();
    
                        if (Country1 == "Ireland")
                        {
                            Console.WriteLine("Thank you!");
                        }
                        else if (Country2 == "UK")
                        {
                            Console.WriteLine("Thank you");
                        }
                        else if (Country3 == "Poland")
                        {
                            Console.WriteLine("Thank you");
                            isvalid = true;
                        }
    
                        
    
                     
    
    
    
                    }
                    catch (FormatException fe)
                    {
                        Console.WriteLine("Wrong country entered! please try again! ");
                    }
    
    
    
                } while (isvalid == false);
    
            }
        }
    }
    

    1) You should never use exceptions to drive your logic. They should only be used to fail gracefully.

    2) Are you trying to force a FormatException? Your code will not do that.
    Look here for some examples of how to do that
    3)
    You're checking against the variable values not the user input

    should be something like
    if(country.equals(Country1))
    {
      ...... do stuff
    }
    


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    One more obeservation
    Your loop as is will never exit as the first if will always evaluate to true so you'll never reach the code where you set isvalid = true

    Couple of other tips
    Since isvalid is a bool you don't need to do the comparison in the condition.
    instead do this
                bool invalid=true;
                ....
                do{
                //set invalid to false in here somewhere
                }while(invalid);
    


    Just one other thing to note, which won't make a difference here but is good to know, is the difference between do while and while.
    A while loop checks the condition before executing the logic.
    A do while loop checks the condition after so it always executes at least once even if the condition evaluates to false.


  • Advertisement
Advertisement