Programming Course in C# ¡Free!


 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a function named "GetInt", which displays on screen the text received as a parameter, asks the user for an integer number, repeats if the number is not between the minimum value and the maximum value which are indicated as parameters, and finally returns the entered number:

age = GetInt("Enter your age", 0, 150);

would become:

Enter your age: 180
Not a valid answer. Must be no more than 150.
Enter your age: -2
Not a valid answer. Must be no less than 0.
Enter your age: 20

(the value for the variable "age" would be 20)



using System;
class Program
public static int getInt( string text, int low, int high)
int result;

result = Convert.ToInt32(Console.ReadLine());
if( result > high )
Console.WriteLine("Must be no more than {0}", higt);

if( result < low )
Console.WriteLine("Must be no less than {0}", low);

while (result < low) || (result > high);

return result;

static void Main()
int age = getInt("Age:  ", 0, 150);