I need help with two similar programs about arrays.
The first program is about that the user can enter any number of numbers between 0 and 9 (input can be made by the
Entering "-1" will be terminated).
After the input is finished, it should be output, how often each number between 0 and 9 was entered.
The 2nd program is about to enter 10 names and save them in a string array. After entering should first all names be output. After that, only those namesare to be issued which were entered more than once.
The Code for the 1. Program :
int cnt = 0;
int input;
while (true)
{
cnt++;
Console.WriteLine("Geben Sie bitte die {0,1}. Zahl ein (-1 für Ende):", cnt);
input = Convert.ToInt32(Console.ReadLine());
int[] count = new int[10];
int[] num = new int[cnt];
if (input > 9)
{
break;
}
else if (input == -1)
{
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < num.Length; y++)
{
if (num[y] == x)
count[x]++;
}
}
//For displaying output only
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
And for the 2nd Program :
int cnt = 10;
string[] name = new string[11];
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Name Nr.{0,1} eingeben: ", i);
name[i]++;
name[i] = Console.ReadLine();
}
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < name.Length; y++)
{
if (i == x)
{
//For displaying output only
for (int a = 0; a < 10; a++)
Console.WriteLine("Folgende Namen wurden mehrfach eingegeben : ", name[i]);
break;
The Problem for the 1st Program is that if i type "-1" The number 1-9 always shows that it appeared 0 times and the number 0 always as an example 4 times when i type 4 numbers.
And for the 2nd is that i really dont know how to put strings in arrays. I want to know how to do that, because of the similarity of these 2 programs.
First of all: don't initialize the arrays every loop iteration. Initialize them on the beginning.
Second thing: you must count the numbers before inputting -1. See that you try to increase the count when you enter -1 whereas -1 meant to be program termination I'm assuming.
And third: ask the second problem with string array as another question. You'll get both answers faster that way.
Here's few alteration of your code that needs to be done.
int input;
int[] count = new int[10];
while (true)
{
Console.WriteLine("Geben Sie bitte die {0,1}. Zahl ein (-1 für Ende): ");
input = Convert.ToInt32(Console.ReadLine());
if(input >= 0 && input <= 9)
{
for (int x = 0; x < 10; ++x)
{
if(x == input)
{
count[x] += 1;
}
}
}
else if (input == -1)
{
//Input finished, display of numbers appearances.
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
break;
}
else
{
break;
}
}
Related
This question already has answers here:
C# How to loop user input until the datatype of the input is correct?
(4 answers)
Closed 3 years ago.
I have a function which asks for input from the user which will be parsed to an int and that will be used to create a pyramid.
I know I have to use a loop of some kind and I have tried a do/while loop but I don't seem to understand it. I can't declare n above the Console.Write outside the do/while and if I have it below inside of the do/while, the while condition wont accept it because it's out of the scope. It would seem so simple to say, do(ask for input and assign to n) while(n <=0), but I can't do that.
I also had an idea I tried which was to run the function within itself as long as n was <=0 but that runs the function infinitely. Not sure if I'm on the right track but I feel lost right now.
static void Pyramid()
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
It should works:
int n;
do
{
Console.Write("Choose a pyramid height: ");
n = Int32.Parse(Console.ReadLine());
if ( n <= 0) Console.WriteLine("Value must be greater than 0.");
}
while ( n <= 0 );
Just use an infinite while loop, and continue if the number is invalid:
static void Pyramid()
{
while(true)
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
if (n <= 0)
{
Console.Error.WriteLine("That's an invalid number");
continue;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
Let's extract method. We should implement 2 checks:
If input is an integer value at all (e.g. "bla-bla-bla" is not an integer)
If input is a valid integer (we don't accept -123)
Code:
public static int ReadInteger(string prompt,
Func<int, bool> validation = null,
string validationMessage = null) {
int result;
while (true) {
if (!string.IsNullOrEmpty(prompt))
Console.WriteLine(prompt);
string input = Console.ReadLine();
if (!int.TryParse(input, out result))
Console.WriteLine("Sorry, your input is not a valid integer value. Please, try again.");
else if (validation != null && !validation(result))
Console.WriteLine(string.IsNullOrEmpty(validationMessage)
? "Sorry the value is invalid. Please, try again"
: validationMessage);
else
return result;
}
}
then you can easily use it:
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0,
"Pyramid height must be positive. Please, try again.");
//TODO: your code here to draw the pyramid of height "n"
please, note, that you can easily restrict the upper bound as well (a pyramid of height 1000000000 will hang the computer):
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0 && value <= 100,
"Pyramid height must be in [1..100] range. Please, try again.");
I am having a hard time with a program I need to write. The requirements are that the user enters in the size of the Array. Then they enter the elements of the array after this the program needs to display the values entered then how many times each value occurs. While everything seems to work except its not display the "occurs" part properly. Lets say "1 1 2 3 4" is entered (Array size being 5) It prints
1 occurs 1 time.
1 occurs 1 time.
2 occurs 1 time.
3 occurs 1 time.
4 occurs 2 times.
this isn't right because 1 occured 2 times and 4 is only 1 time. Please Help...
static void Main(string[] args)
{
int[] arr = new int[30];
int size,
count=0,
count1=0,
count2=0;
Console.Write("Enter Size of the Array: ");
size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i=0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Values Entered: \n");
for (int i = 0; i < size; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] <= 10)
count++;
else
count1++;
}
for(int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j])
count2++;
else
count2 = 1;
}
Console.WriteLine(arr[i] + " Occurs " + count2 + " Times.");
}
Console.WriteLine("The number of valid entries are: " + count + "\nThe number of invalid entries are: " + count1);
Console.ReadKey();
}
if you can use Linq, this is easy job:
After
Console.Write("Values Entered: \n");
add
var grouped = arr.GroupBy(x => x);
foreach (var group in grouped)
{
Console.WriteLine("number {0} occurs {1} times", group.Key, group.Count());
}
EDIT
Since OP isn't allowed to use Linq, here's array-only solution. Much more code than that dictionary approach, but with arrays only.
Console.Write("Values Entered: \n");
//an array to hold numbers that are already processed/counted. Inital length is as same as original array's
int[] doneNumbers = new int[arr.Length];
//counter for processed numbers
int doneCount = 0;
//first loop
foreach (var element in arr)
{
//flag to skip already processed number
bool skip = false;
//check if current number is already in "done" array
foreach (int i in doneNumbers)
{
//it is!
if (i == element)
{
//set skip flag
skip = true;
break;
}
}
//this number is already processed, exit loop to go to next one
if (skip)
continue;
//it hasn't been processed yes, so go through another loop to count occurrences
int occursCounter = 0;
foreach (var element2 in arr)
{
if (element2 == element)
occursCounter++;
}
//number is processed, add it to "done" list and increase "done" counter
doneNumbers[doneCount] = element;
doneCount++;
Console.WriteLine("number {0} occurs {1} times", element, occursCounter);
}
You can simply use dictionary:
static void Main(string[] args)
{
var dic = new Dictionary<int, int>();
Console.Write("Enter Size of the Array: ");
int size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i = 0; i < size; i++)
{
int val = Convert.ToInt32(Console.ReadLine());
int current;
if (dic.TryGetValue(i, out current))
{
dic[val] = current + 1;
}
else
{
dic.Add(val, 1);
}
}
foreach (int key in dic.Keys)
{
Console.WriteLine(key + " Occurs " + dic[key] + " Times.");
}
Console.Read();
}
The problem is that you're resetting count2 to 1 any time you find a mismatch.
What you should do instead is set count2 to 0 in the outer loop (so it basically resets once for each item), and then let the inner loop count all the instances of that number:
// For each item 'i' in the array, count how many other items 'j' are the same
for (int i = 0; i < size; i++)
{
count2 = 0; // processing a new item, so reset count2 to 0
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j]) count2++;
}
Console.WriteLine(arr[i] + " occurs " + count2 + " times.");
}
I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}
I am trying to achieve the following:
User enters 100 numbers and then the numbers are printed in 3 columns.
This is what I have so far, it works but it does not print the last value of the array.
What am I doing wrong?
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 100;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
digit = int.Parse(Console.ReadLine());
row[i] = digit;
}
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
}
Use this print instead
for (int i = 0; i < row.Length; i++)
{
Console.Write(row[i] + "\t");
if (i % 3 == 2)
Console.WriteLine();
}
Your issue is that you don't simply use Console.Write, and try to write your lines in one shot.
In fact, it would be even cleaner to use a StringBuilder here.
Replace
for (int i = 0; i < row.Length - 2; i+=3)
{
Console.WriteLine(row[i] + "\t" + row[i + 1] + "\t" + row[i + 2]);
}
by
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < row.Length; i++)
{
count++;
if (count == 3)
{
sb.AppendLine(row[i])
count = 0;
}
else
sb.Append(row[i]).Append('\t');
}
Console.WriteLine(sb.ToString());
I think it's pretty explicit, but if you need clarifications, feel free to ask. Of course, the use of count here is pretty scholar, a real program could use % operator, like shown in other answers.
You have wrong condition in for loop. If you don't mind LINQ, you can use the following:
foreach (string s in row.Select((n, i) => new { n, i })
.GroupBy(p => p.i / 3)
.Select(g => string.Join("\t", g.Select(p => p.n))))
Console.WriteLine(s);
If you're not ok with LINQ, you can do this:
int colIndex = 0;
foreach (int n in row)
{
Console.Write(n);
if (colIndex == 2)
Console.WriteLine();
else
Console.Write('\t');
colIndex = (colIndex + 1) % 3;
}
jonavo is correct.
after 96+3 = 99
and you have done row.length-2, change it to row. length+2.
and in print dont print if the i+1 or I+2 >= max
It doesn't print it because 100 is not evenly divisible by 3 and your for-loop increases the variable by 3 on each iteration, so the last element wil be skipped.
Maybe this after the loop:
int rest = row.Length % 3;
if(rest > 0)
Console.WriteLine(row[row.Length - rest] + "\t" + row.ElementAtOrDefault(row.Length - rest + 1));
Its because of your index.
Your running index i goes from
0, 3, 6, 9, ... 96, 99
So this would output the array positions:
0,1,2 3,4,5 6,7,8 9,10,11 ... 96,97,98 99,100,101 (index out of bounds)
row.Length equals 100, so your loop-condition (i < row.Length - 2) is correct, but even better would be (i < row.Length - 3).
So your problem is how to print the last number... You see, you have 3 columns for 100 digits. This makes 33 rows and than there is one digit left.
Maybe you just add some Console.WriteLine(row[row.Length-1]); beneeth your loop.
Looks like you've got a lot of options at your disposal. Here's an approach using nested loops:
int numCols = 3;
for (int i = 0; i < row.Length; i += numCols)
{
for (int j = i; j < i + numCols && j < row.Length; j++)
{
Console.Write(row[j] + "\t");
}
Console.WriteLine();
}
Try this code.
Using this loop you can also change the number of rows/columns without code changes. Also, using the temporary buffer you output to the console an entire row at a time.
static void Main(string[] args)
{
int digit = 0;
const int LIMIT = 10;
const int COLS = 3;
int[] row = new int[LIMIT];
for (int i = 0; i < row.Length; i++)
{
Console.WriteLine("Geef getal nummer " + (i + 1) + " in: ");
// Re-try until user insert a valid integer.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
row[i] = digit;
}
PrintArray(row, COLS);
// Wait to see console output.
Console.ReadKey();
}
/// <summary>
/// Print an array on console formatted in a number of columns.
/// </summary>
/// <param name="array">Input Array</param>
/// <param name="columns">Number of columns</param>
/// <returns>True on success, otherwise false.</returns>
static bool PrintArray(int[] array, int columns)
{
if (array == null || columns <= 0)
return false;
if (array.Length == 0)
return true;
// Build a buffer of columns elements.
string buffer = array[0].ToString();
for (int i = 1; i < array.Length; ++i)
{
if (i % columns == 0)
{
Console.WriteLine(buffer);
buffer = array[i].ToString();
}
else
buffer += "\t" + array[i].ToString();
}
// Print the remaining elements
if (array.Length % columns != 0)
Console.WriteLine(buffer);
return true;
}
Just for completeness
Note that int.Parse(Console.ReadLine()) can throw an Exception if unexpected characters are typed. It's better to use int.TryParse() as documented here. This method don't throw an exception but return a boolean that report a successful conversion.
while (!int.TryParse(Console.ReadLine(), out digit))
Console.WriteLine("Wrong format: please insert an integer number:");
This code tell the user that the typed string can't be interpreted as an integer and prompt again until a successful conversion is done.
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]);
}
}