I need to create 2 methods. Method 1 (CreateArray) shall allow the user to enter the length of an array they would like to create and then enter the value for each element. Method 2 (PrintArray) prints the array created in Method 1.
Both methods work fine on a standalone basis. However, I don't know how to pass CreateArray method to PrintArray method.
class Calculation
{
public int[] CreateArray (int a)
{
int count = 1;
int[] CreateArray = new int[a];
for (int i = 0; i < CreateArray.Length; i++)
{
Console.Write($"{count}.) Enter a value - ");
int userInput = int.Parse(Console.ReadLine());
CreateArray[i] = userInput;
count++;
}
return CreateArray;
}
public void PrintArray(int[] numbers)
{
int elementNum = 1;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"{elementNum}.) {numbers[i]}");
elementNum++;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the Length of an array you would like to create: ");
int arrayLength = int.Parse(Console.ReadLine());
Calculation calc = new Calculation();
calc.CreateArray(arrayLength);
}
}
You need to store the results of "calc.CreateArray(arrayLength);" in a local variable and pass it to PrintArray():
int[] newArray = calc.CreateArray(arrayLength);
calc.PrintArray(newArray);
Related
My main goal is to create a Method, where it is possible to enter a number, out of which a Method will choose some other numbers (according to the purpose) and combine them in Array.
I need this Array and its value to be flexible, so I decided to create a new variable, that is within the scope for both Container() and Main() methods. Then I assigned a value from Container() to optainer, but it didn't work (foreach doesn't display all numbers from Container(), only the first one). Where is my problem?
static int[] optainer;
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer = new int[] { i };
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
// Expected: few numbers according to the condition; Real result: 1
```
You have always only one element in optainer,
this line is the error
optainer = new int[] { i }; you create always a new array with only one item and the last is always 1.
you can change in this way
static List<int> optainer = new List<int>();
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
}
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer.Add(i);
}
}
}
I'm sure there's a sexier way to do this, but try this:
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
int size = optainer.Length + 1;
Array.Resize(ref optainer, size);
optainer[size - 1] = i;
}
}
}
Everytime you write
optainer = new int[] { i };
you create a new list(you overwrite the old one) you would have to append
to the array. Therefore you would need to know the size of the array.
To save memory you should use something more dynamic like lists.
Here is an explanation how to add a value:
Adding values to a C# array
I am getting an error while taking array input from the user.
static void Main(string[] args)
{
int[] arrSum = new int[] { };
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for (int i = 0; i < n; i++)
{
arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);
}
public static int ArraySum(int[] arr, int key, int n)
{
for (int i = 0; i < arr.Length; i++)
{
int first = arr[i];
for (int k = i+1; k < arr.Length; k++)
{
int second = arr[k];
while (first + second == key)
{
Console.WriteLine("The numbers whose sum is {0}" + key + "are:\n" + first + second);
}
if (first + second != key)
{
return -1;
}
else
{
return 1;
}
}
}
return 0;
}
To take array size and elements and the number whose sum we need to compare among the given array elements from the user as input and return the possible pairs whose sum is equal to the given number.
I am not sure if I met the same problem as you, but I modified your code as following. At first I created a safe console readline method for integer that there is no exception thrown if an invalid integer is entered:
private static int GetIntFromInput()
{
while (true)
{
string value = Console.ReadLine();
if (!int.TryParse(value, out int parsedInt))
{
Console.WriteLine("Invalid integer! Retry or Ctrl+C to abort program...");
continue;
}
return parsedInt;
}
}
Then I modified your first method as following:
static void Main(string[] args)
{
Console.WriteLine("Enter the array Size:\t");
int n = GetIntFromInput();
if (n <= 0)
{
Console.WriteLine("Array has to be at least of size 1...");
return;
}
Console.WriteLine("Enter the array elements of {0} as Array Size:\n", n);
var arrSum = new int[n];
for (int i = 0; i < n; i++)
{
int newInt = GetIntFromInput();
arrSum[i] = newInt;
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum, n, j);
}
With this my tests had been successful. Please note, that I did not replace the last Convert.ToInt32 for j.
As a note, please always verify user input as far as possible for not throwing exceptions. If anytime you will check anything not correctly it will crash sometime for sure...
have a great day!
I just have modified your array input code lines, pretty much straight forward. You can use int.TryParse as well just in case you wish to have a check
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
int[] arrSum = new int[n];
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for(int i = 0;i<n;i++){
arrSum[i]= Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);
Im completely new to coding and I've been given a challenge to create a histogram by asking a user to input a certain amount of numbers line by line. Which I have executed a for loop to handle with no issues. The difficulty I'm having is I'm trying to use a string which I've called (x) and contains (""). The challenge is to make the () symbol duplicate to the amount of the value entered by the user... Just wondering how I could code it in such a way so that it compares the user input value number to print the (*) the same amount equal to the number being entered!
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
string x = ("*");
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
for (int count= 0; count < userVal.Length; count ++)
{
}
A simple way might be to iterate through the responses, and use the string(char,cnt) constructor https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx.
It fills the string with a specific char, and specific length.
e.g.
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int numberToCollect = 10;
int[] answers = new int[numberToCollect];
int numberCollected = 0;
while(numberCollected<numberToCollect)
{
int parsedInt = 0;
if (int.TryParse(intConsole.ReadLine(),out parsedInt))
{
answers[numberCollected++] = parsedInt;
}
else
{
Console.WriteLine("Invalid number, try again!");
}
}
for(var cnt in answers)
{
Console.WriteLine(new String('*',cnt));
}
}
}
}
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
foreach (var cnt in userVal)
{
Console.WriteLine(new String('*', cnt));
}
Console.ReadKey();
}
}
}
I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}
I am trying to ask the user to input 10 numbers. After receiving the numbers, I am storing them in an array followed by printing the array. I came up with the following code to do the task but it is not printing the array.
Also feel that I may have rattled on way too much code for a simple task. Do note that I am very new to c# thus not familiar with advanced stuff or possibly even most of basic stuff. Even the "convert.toInt32", I adopted from reading around and not taught in class yet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_Array
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = Convert.ToInt32(Console.ReadLine());
e = Convert.ToInt32(Console.ReadLine());
f = Convert.ToInt32(Console.ReadLine());
g = Convert.ToInt32(Console.ReadLine());
h = Convert.ToInt32(Console.ReadLine());
i = Convert.ToInt32(Console.ReadLine());
j = Convert.ToInt32(Console.ReadLine());
int[] newArray = {a,b,c,d,e,f,g,h,i,j};
Console.WriteLine(newArray);
Console.ReadLine();
}
}
}
use a for loop.
int[] newArray = new int[10];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
You can use the same loop to display as well:
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
The ToString method of arrays (which is what Console.WriteLine is calling in your code) isn't overloaded to print out the contents of the array. It leaves the basic object implementation of just printing the type name.
You need to manually iterate the array and print out the individual values (or use a method that will do that for you).
I.e.
foreach(var item in array)
Console.WriteLine(item)
or
Console.WriteLine(string.Join("\n", array));
static void Main(string[] args)
{
int[] rollno = new int[10];
Console.WriteLine("Enter the 10 numbers");
for (int s = 0; s < 9; s++)
{
rollno[s] = Convert.ToInt32(Console.ReadLine());
rollno[s] += 110;
}
for (int j = 0; j < 9; j++)
{
Console.WriteLine("The sum of first 10 numbers is : {0}", rollno[j]);
}
Console.ReadLine();
}
}
}
You could simplify things a lot with the following:
static void Main(string[] args)
{
int newArray = new int[10];
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
for (int i = 0; i < 10; i++) {
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The values you've entered are:");
Console.WriteLine(String.Join(", ", newArray));
Console.ReadLine();
}