Passing Arrays as Parameters in C# - c#

I am trying to create a function that accepts 5 integers, holds them in an array and then passes that array back to the main. I have wrestled with it for a couple of hours and read some MSDN docs on it, but it hasn't "clicked". Can someone please shed some light as to what I am doing wrong?
Errors:
Not all code paths return a value;
something about invalid arguments:
Code:
using System;
using System.IO;
using System.Text;
namespace ANumArrayAPP
{
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
}
}
}

The parameter to ReadInNum is a single int, but you're trying to pass an array. You have to make the parameter match what you're trying to pass in. For example:
static void ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readIn[i] = int.Parse(Console.ReadLine());
}
}
That will fill the array you pass into the method. Another alternative is to pass in how many integers you want, and return the array from the method:
static int[] ReadInNum(int count)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
Console.WriteLine("Please enter an interger");
values[i] = int.Parse(Console.ReadLine());
}
return values;
}
You'd call this from Main like this:
int[] input = ReadInNum(5);
for (int a = 0; a < 5; a++)
{
Console.Write(input[a]);
}

You should complete your function with return statement since its return type is not void. Also, you should change your return type to int[] since your return an array of ints, not just one int:
static int[] ReadInNum(int readIn)
{
int[] readInn = new int[5];
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readInn;
}
You should also change your main function in order to get the result of the function ReadInNum. It seems to me that you don't really use the parameter so you can remove it, if you don't have special attention:
static void Main()
{
int j;
int[] i = ReadInNum(j);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}

To summarize zome aswer already here, there are two ways to go about it:
1. Pass an array into the method
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(i[a]); // !
}
}
static int ReadInNum(int[] readIn)
{
for (int i = 0; i < rreadIn.Length; i++)
...
}
2. Return an array
static void Main()
{
// int[] i = new int[5];
int[] i = ReadInNum(5);
for (int a = 0; a < i.Length; a++)
{
Console.Write(i[a]); // !
}
}
static int[] ReadInNum(int size)
{
int[] readIn = new int[size];
for (int i = 0; i < readIn.Length; i++)
...
}

Pass an array to the function:
class Program
{
static void Main()
{
int[] i = new int[5];
ReadInNum(i);
for (int a = 0; a < 5; a++)
{
Console.Write(a);
}
}
static int[] ReadInNum(int[] readIn)
{
for (int i = 0; i < readIn.Length; i++)
{
Console.WriteLine("Please enter an interger");
readInn[i] = Console.Read();
}
return readIn;
}
}
Notice how I returned an int[] from ReadInNum. This isn't necessary but it makes the code more readable since it's not more obvious that you're planning on changing readIn.

Related

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

Comparasion of numbers in an array

I'm stuck at this. I`m beginner into software development.
You get a list of N students and then a list of ratings for each student. A student which has bigger rating than his neighbour from list gets more candies than both of them. For example:
Data input:
3
John
Michael
Sam
9
10
8
Data Output:
John 1
Michael 3
Sam 1
I wrote this code, but I'm missing something:
using System.Diagnostics.CodeAnalysis;
using System.IO.Pipes;
{
int number = Convert.ToInt32(Console.ReadLine());
string[] studentsList = FillArray(number);
int[] studentsGrades = ConvertList(FillArray(number));
PrintResult(studentsList, CountCandies(int number));
}
static string[] FillArray(int number)
{
string[] result = new string[number];
for (int i = 0; i < number; i++)
{
result[i] = Console.ReadLine();
}
return result;
}
static int[] ConvertList(string[] array)
{
int[] result = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = Convert.ToInt32(array[i]);
}
return result;
}
static int[] GetGrades(int number) // give grades of each student
{
int[] result = new int[number];
for (int i = 0; i < number; i++)
{
result[i] = Convert.ToInt32(Console.ReadLine());
}
return result;
}
static int CountCandies(int[] arr, int number) // this is the method where I'm stuck.
{
int sum = 0;
int[] ans = new int[number];
for (int i = 0; i < number; i++)
{
ans[i] = 1;
}
for (int i = 0; i < number-1; i++)
{
if (arr[i+1] > arr[i])
{
ans[i+1] =ans[i] +1;
}
}
for (int i = number-2; i>=0; i--)
{
if (arr[i] > arr[i+1] && ans[i] <= ans[i+1])
{
ans[i] = ans[i+1] +1;
}
sum += ans[i];
}
sum += ans[number-1];
return sum;
}
static void PrintResult(string[] array, int[] array2) // print the final result
{
for (int i = 0; i < array.Length; i++)
{
array[i] += " " + array2[i];
}
foreach (string student in array)
{
Console.WriteLine(student);
}
}
You definitely need an object to hold your data.
public class StudentRating
{
public string StudentName {get;set;}
public int Rating {get;set;}
}
protected List<StudentRating> studentsRating = new List<StudentRating>();
public static void Main(string[] args)
{
GeteringInformation();
//after this do what you want with your data
}
protected static GeteringInformation()
{
Console.WriteLine("Student name:");
int rating =Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Rating");
string name =Console.ReadLine();
studentsRating.Add(new StudentRating(){StudentName=name,Rating=rating});
Console.WriteLine("Next? (Y/N)");
if(Console.ReadLine().ToLower()="y")
GeteringInformation();
}

Sort by selection in C#

I am a complete beginner in programming. Trying to make sorting a choice. Everything seems to be ok. Only there is one caveat. Only numbers up to 24 index are filled in the new array. I can’t understand what the problem is.
int[] Fillin(int[] mass)
{
Random r = new Random();
for(int i = 0; i < mass.Length; i++)
{
mass[i] = r.Next(1, 101);
}
return mass;
}
int SearchSmall(int[] mass)
{
int smallest = mass[0];
int small_index = 0;
for(int i = 1; i < mass.Length; i++)
{
if (mass[i] < smallest)
{
smallest = mass[i];
small_index = i;
}
}
return small_index;
}
int[] Remove(int[] massiv,int remind)
{
List<int> tmp = new List<int>(massiv);
tmp.RemoveAt(remind);
massiv = tmp.ToArray();
return massiv;
}
public int[] SortMass(int[] mass)
{
mass = Fillin(mass);
Print(mass);
Console.WriteLine("________________________________");
int[] newmass = new int[mass.Length];
int small;
for(int i = 0; i < mass.Length; i++)
{
small = SearchSmall(mass);
newmass[i] = mass[small];
mass = Remove(mass, small);
}
return newmass;
}
I think your main issue is that when you remove an element in the Remove function, the main loop in for (int i = 0; i < mass.Length; i++) will not check all elements o the initial array. A simple (and ugly) way to fix that would be not to remove the elements but to assign a very high value
public static int[] Remove(int[] massiv, int remind)
{
massiv[remind] = 999999;
return massiv;
}
Or as Legacy suggested simply modify the mass.length for newmass.lengh in the main loop.
As some others have mentioned this is not the best way to order an array, but it is an interesting exercise.

How can i use methods in c#?

So, I have to do homework about methods in c#. I am confused about some points. I wrote methods (they may be wrong) but I don't know how to call them. How can I write this part? For example finding max value. What can I write? I tried a lot of times but couldn't handle it.
Also, this code has to be kept in a txt file but doesn't.
public static void WriteData(StreamWriter sw)
{
int[,] a = new int[4, 6];
Random rnd = new Random();
for (int i = 0; i < a.GetLength(0); i++)
{
for (int J = 0; J < a.GetLength(1); J++)
{
a[i, J] = rnd.Next(10, 100);
}
}
Console.WriteLine("\nMATRIX:");
for (int i = 0; i < a.GetLength(0); i++)
{
for (int J = 0; J < a.GetLength(1); J++)
{
Console.Write("{0,-4}", a[i, J]);
}
Console.WriteLine();
}
Console.WriteLine("\nTRANSPOSE:");
for (int i = 0; i < a.GetLength(1); i++)
{
for (int J = 0; J < a.GetLength(0); J++)
{
Console.Write("{0,-4}", a[J, i]);
}
Console.WriteLine();
}
}
public static void DisplayMatrix(int[,] a)
{
Console.WriteLine("{0}", a);
}
public static int MaxNumber(int[] a)
{
int max = a[0];
for (int i = 0; i < a.Length; i++)
{
if (max < a[i])
{ max = a[i]; }
}
return max;
}
public static void DisplayOddOrEvenForMax(int max)
{
if (max % 2 == 0)
{
Console.WriteLine("Number is even");
}
else
{
Console.WriteLine("Number is odd");
}
}
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("MyMatrix.txt", true);
WriteData(sw);
sw.Close();
`
Methods are (usually) either attached to a class or are static
if you have a class like this:
class MyClass {
void myMethod() {
//do something
}
}
then you have to create an instance of that class , so something like this:
MyClass foo = new MyClass() //here foo is the name of the instance
and then call that method on that instance
foo.myMethod()
if the method is static like this:
class MyClass {
static void myMethod() {
//do something
}
}
then that method does can be run directly by calling it, along with the class that contains it, so something like this:
MyClass.myMethod()
I hope this helped

How can I fill array with unique random numbers with for-loop&if-statement?

I'm trying to fill one dimensional array with random BUT unique numbers (No single number should be same). As I guess I have a logical error in second for loop, but can't get it right.
P.S I'm not looking for a more "complex" solution - all I know at is this time is while,for,if.
P.P.S I know that it's a really beginner's problem and feel sorry for this kind of question.
int[] x = new int[10];
for (int i = 0; i < x.Length; i++)
{
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) break;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i);
}
Here is a solution with your code.
int[] x = new int[10];
for (int i = 0; i < x.Length;)
{
bool stop = false;
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) {
stop = true;
break;
}
}
if (!stop)
i++;
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
A simple trace of the posted code reveals some of the issues. To be specific, on the line…
if (x[i] == x[j]) break;
if the random number is “already” in the array, then simply breaking out of the j loop is going to SKIP the current i value into the x array. This means that whenever a duplicate is found, x[i] is going to be 0 (zero) the default value, then skipped.
The outer i loop is obviously looping through the x int array, this is pretty clear and looks ok. However, the second inner loop can’t really be a for loop… and here’s why… basically you need to find a random int, then loop through the existing ints to see if it already exists. Given this, in theory you could grab the same random number “many” times over before getting a unique one. Therefore, in this scenario… you really have NO idea how many times you will loop around before you find this unique number.
With that said, it may help to “break” your problem down. I am guessing a “method” that returns a “unique” int compared to the existing ints in the x array, may come in handy. Create an endless while loop, inside this loop, we would grab a random number, then loop through the “existing” ints. If the random number is not a duplicate, then we can simply return this value. This is all this method does and it may look something like below.
private static int GetNextInt(Random r, int[] x, int numberOfRandsFound) {
int currentRand;
bool itemAlreadyExist = false;
while (true) {
currentRand = r.Next(RandomNumberSize);
itemAlreadyExist = false;
for (int i = 0; i < numberOfRandsFound; i++) {
if (x[i] == currentRand) {
itemAlreadyExist = true;
break;
}
}
if (!itemAlreadyExist) {
return currentRand;
}
}
}
NOTE: Here would be a good time to describe a possible endless loop in this code…
Currently, the random numbers and the size of the array are the same, however, if the array size is “larger” than the random number spread, then the code above will NEVER exit. Example, if the current x array is set to size 11 and the random numbers is left at 10, then you will never be able to set the x[10] item since ALL possible random numbers are already used. I hope that makes sense.
Once we have the method above… the rest should be fairly straight forward.
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
int numberOfRandsFound = 0;
int[] ArrayOfInts = new int[DataSize];
int currentRand;
for (int i = 0; i < ArrayOfInts.Length; i++) {
currentRand = GetNextInt(random, ArrayOfInts, numberOfRandsFound);
ArrayOfInts[i] = currentRand;
numberOfRandsFound++;
}
for (int i = 0; i < ArrayOfInts.Length; i++) {
Console.WriteLine(ArrayOfInts[i]);
}
Console.ReadKey();
}
Lastly as other have mentioned, this is much easier with a List<int>…
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
List<int> listOfInts = new List<int>();
bool stillWorking = true;
int currentRand;
while (stillWorking) {
currentRand = random.Next(RandomNumberSize);
if (!listOfInts.Contains(currentRand)) {
listOfInts.Add(currentRand);
if (listOfInts.Count == DataSize)
stillWorking = false;
}
}
for (int i = 0; i < listOfInts.Count; i++) {
Console.WriteLine(i + " - " + listOfInts[i]);
}
Console.ReadKey();
}
Hope this helps ;-)
The typical solution is to generate the entire potential set in sequence (in this case an array with values from 0 to 9). Then shuffle the sequence.
private static Random rng = new Random();
public static void Shuffle(int[] items)
{
int n = list.Length;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
int temp = items[k];
items[k] = items[n];
items[n] = temp;
}
}
static void Main(string[] args)
{
int[] x = new int[10];
for(int i = 0; i<x.Length; i++)
{
x[i] = i;
}
Shuffle(x);
for(int i = 0; i < x.Length; i++)
{
Console.WritLine(x[i]);
}
}
//alternate version of Main()
static void Main(string[] args)
{
var x = Enumerable.Range(0,10).ToArray();
Shuffle(x);
Console.WriteLine(String.Join("\n", x));
}
You can simply do this:
private void AddUniqueNumber()
{
Random r = new Random();
List<int> uniqueList = new List<int>();
int num = 0, count = 10;
for (int i = 0; i < count; i++)
{
num = r.Next(count);
if (!uniqueList.Contains(num))
uniqueList.Add(num);
}
}
Or:
int[] x = new int[10];
Random r1 = new Random();
int num = 0;
for (int i = 0; i < x.Length; i++)
{
num = r1.Next(10);
x[num] = num;
}

Categories