return and while in function - c#

This function accepting input and telling the user whether the input is number or not a number.
static string isnum()
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
return "";
}
}
isnum();
I would like this function to repeat herself if the input is not a number, till the input will be a number, and then to stop.
This function working now, but she's working only one time.
When I'm trying to add a while block to the function to make her run again and again till the input is number I'm getting the "not all code paths return a value" error.
is it because a "return" statement ends a function, and therefore prevent her to run again?
how can I solve that?
Thank you very much!

You can fix this with creating a loop arround it and do not return when it's not a number.
static string isnum()
{
// just loop forever.
while (true)
{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
// don't return here
}
}
}

In this case the best approach is to use do while because you want your code to at least run once.
you have one problem in your code which is returning when variable is not a number. see these modifications:
static string isnum()
{
do{
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
string nums = "123456789";
int cnt = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (a[i] == nums[j])
{
cnt++;
break;
}
}
}
if (cnt == a.Length)
{
Console.WriteLine(a + " is a number");
return a;
}
else
{
Console.WriteLine(a + " is not a number");
}
}while(true);
}

Call it in a while loop, and loop until the result is a number:
string result = "";
while (result == "")
{
result = isnum();
}
Console.WriteLine("result is a number: " + result);

Instead of looping you can try querying the a string with a help of Linq:
using System.Linq;
...
static string isnum() {
// Keep asking user until he/she provides a number
while (true) {
Console.WriteLine("Write a number please");
string a = Console.ReadLine();
// Number is
// 1. Has at least one character
// 2. All characters of number are digits
if (a.Length > 0 && a.All(c => c >= '0' && c <= '9')) {
Console.WriteLine($"{a} is a number");
// we have a proper number, let's return int
return a;
}
Console.WriteLine($"{a} is not a number");
}
}

Related

school homework - grade calculation

i have got questions.
my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?
int not;
bool test = true;
for (int i = 0; i < 20; i++)
{
Console.Write((i + 1) + (".Not:"));
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
test = false;
Console.Write("Try again!");
}
else
{
test = true;
}
}
I want to use bool while doing this. would be glad if you help. thank you in advance
i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?
int not;
int temp = 0;
for (int i = 0; i < 20; i++)
{
Console.Write("Add Not : ");
backtoAdd:
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
Console.WriteLine("Try Again!");
goto backtoAdd;
}
Console.WriteLine((i+1)+". Not : "+not);
temp = temp + not;
}
Console.Write("sum of not : "+temp);
Console.ReadKey();
As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:
// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;
// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
// we give input
string? input = Console.ReadLine();
// we try to parse our input
var parsed = int.TryParse(input, out var grade);
// if our input is parsed correctly
if (parsed)
{
// we check if the input value between the given range
if (grade < lowestGrade || grade > highestGrade)
{
Console.WriteLine("Try Again!");
}
else
{
// if with in range count
counter++;
}
}
}

breaks while loop when all die rolls the same number

using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}

C# How do I use a variable outside of a loop that changes from string to int inside the loop?

The code:
string[] numbers = new string[2];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Console.ReadLine();
if (int.TryParse(numbers[i], out int numberTry) && i == 0)
Console.WriteLine("That would be a number yes.");
else if (int.TryParse(numbers[i], out numberTry))
Console.WriteLine("Lovely work! That is indeed two numbers!");
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
My problem here is that I can't use numbers[] outside of the loop as an int because it chancges from a string to an int inside of the loop. I need to be able to send it with a method as an int to perform a operation on numbers[0] and numbers[1].
Thanks in advance!
Could you try this. It should work.
int[] numbers = new int[2];
for (int i = 0; i < numbers.Length; i++)
{
var number = Console.ReadLine();
if (int.TryParse(number, out int numberTry) && i == 0)
{
Console.WriteLine("That would be a number yes.");
numbers[i] = numberTry;
}
else if (int.TryParse(number, out numberTry))
{
Console.WriteLine("Lovely work! That is indeed two numbers!");
numbers[i] = numberTry;
}
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
Console.ReadKey();

How to add elements to an array based on a condition?

I'm working on this simple C# program adding elements to an array. I allow the user to enter 5 numbers, and if the user enters an INVALID valid I have a message for that. My issue is that whether the users enters an invalid number or not I still want to add 5 numbers to my array.
My code works, but let's say the user enters 3 numbers and then 2 words and I end up having ONLY 3 numbers, but I want the 5 numbers no matter what. What am I doing wrong?
Here's my code:
int[] numbers = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
You can reduced increment count by 1, when user inputs wrong/no number.
Also note, you are code currently reading input only for 4(not 5 as question description says.) numbers.
int[] numbers = new int[4];
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
}
else
{
i--;
Console.WriteLine("You did not enter a number\n");
}
}
for (int i = 0; i < numbers.Length; i++ )
{
Console.Write(numbers[i] + " ");
}
try using do-while
int[] numbers = new int[4];
int i = 0;
do
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value))
{
numbers[i] = value;
i++;
}
else
{
Console.WriteLine("You did not enter a number\n");
}
} while (i < 5);
Console.WriteLine("\nYour entered numbers are\n");
for (int j = 0; j < numbers.Length; j++ )
{
Console.Write(numbers[j] + " ");
}
You could use while loop here. See the below code
int[] numbers = new int[5];
int i = 0;
while (i < 5) {
Console.WriteLine ("Enter a number: ");
string c = Console.ReadLine ();
int value;
if (int.TryParse (c, out value)) {
numbers[i] = value;
i++;
} else {
Console.WriteLine ("You did not enter a number\n");
}
}
for (i = 0; i < numbers.Length; i++) {
Console.Write (numbers[i] + " ");
}
You can reduce the code using while loop. Also its better to change the last for loop to foreach
int[] numbers = new int[5];
int i = 0;
while (i < 5)
{
Console.WriteLine("Enter a number: ");
string c = Console.ReadLine();
int value;
if (!int.TryParse(c, out value)) continue;
numbers[i] = value;
i++;
}
foreach (int t in numbers)
Console.Write(t + " ");

Array Duplicate Elimination with c#?

I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}

Categories