C# use of unassigned local variable....confused - c#

trying to iterate with this for loop and input int from user into array. I am getting an error and don't understand why..
error: Error 1 Use of unassigned local variable 'array'
using System;
namespace Lab16
{
class Program
{
static void Main(string[] args)
{
int[] array;
int value;
Console.Write("How big of an Array? ");
int arraySize = int.Parse(Console.ReadLine());
for (int i = 0; i <= arraySize; i++)
{
Console.Write("First Value: ");
value = int.Parse(Console.ReadLine());
--> array[i] = Convert.ToInt32(value);
}
}
}
}

Your array variable isn't initialized. Writing this should fix it:
int[] array = new int[arraySize];
(Note, of course this needs to go after you've read arraySize from the console...)
int value;
Console.Write("How big of an Array? ");
int arraySize = int.Parse(Console.ReadLine());
int[] array = new int[arraySize];
And one more problem ... your for loop as written is going to go out of bounds. Should be like this:
for (int i = 0; i < arraySize; i++)

Local variables in C# are not initialized/assigned implicitly. Here in your code snippet, you need to create an array.
int[] array=new int[arraySize];

You need to initialize the array once you know how big it should be.
You also need to iterate from 0 to arraySize-1 - so I changed your <= to <:
Console.Write("How big of an Array? ");
int arraySize = int.Parse(Console.ReadLine());
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
Console.Write("Value: ");
int value = int.Parse(Console.ReadLine());
array[i] = Convert.ToInt32(value);
}
If the user enters 10 for the length, you will initialize the array to length 10 - and then you can access elements 0 to 9, which is 10 separate elements.

You need to initialize the array, but you declare it before you know the size it needs to be.
using System;
namespace Lab16
{
class Program
{
static void Main(string[] args)
{
int arraySize;
int arrayValue;
Console.WriteLine("How big of an Array? ");
while(!int.TryParse(Console.ReadLine(), out arraySize))
{
Console.WriteLine("How big of an Array? ");
}
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
Console.WriteLine(string.Format("Value of element {0}: ", i));
while(!int.TryParse(Console.ReadLine(), out arrayValue))
Console.WriteLine(string.Format("Value of element {0}: ", i));
array[i] = arrayValue;
}
}
}
}

Related

is there a way to have line amount higher than 6, when my array bound is set to 6?

I would like to print out more than six lines of six random numbers, but array bound is blocking me. I have set my array 'numbers' to six in order to always get just six random numbers, but now I dont know what to do to print out for example just ten lines of the numbers, because as I said - I can not due to six bounded array and I do not know how to deal with it. Can anyone help, please?
using System;
class Program
{
static void Main()
{
Draw();
Console.ReadKey();
}
static void Draw()
{
int choice;
Random randomNum = new Random();
int[] numbers = new int[6];
Console.Write("enter line amount: ");
choice = int.Parse(Console.ReadLine());
for (int i = 0; i < choice; i++)
{
Console.Write("\n");
for (int j = 0; j < numbers.Length; j++)
{
numbers[i] = randomNum.Next(1, 49);
Console.Write("{0} ", numbers[i]);
}
}
}
}
Hy!
In the 2nd for loop, write "j" instead of "i", because the 2nd for loop monitors the length of the array
Try this:
static void Main(string[] args)
{
Draw();
Console.ReadKey();
}
static void Draw()
{
int choice;
Random randomNum = new Random();
int[] numbers = new int[6];
Console.Write("enter line amount: ");
choice = int.Parse(Console.ReadLine());
for (int i = 0; i < choice; i++)
{
Console.Write("\n");
for (int j = 0; j < numbers.Length; j++)
{
numbers[j] = randomNum.Next(1, 49);
Console.Write("{0} ", numbers[j]);
}
}
}
Arrays in C# are of a fixed size, so I'd recommend using a dynamically-sized collection, such as a List<T> instead in your case.
There's a good introduction on how to use these on Microsoft's documentation here if you aren't familiar.

I just can't insert more than 5 elements in a array in C#

I'm trying to make a simple program where I declare the size of an array with one input, but I gives an IndexOutOfRange Exception if the array has more than 5 elements. Somebody can help me understand why, please?
class Program
{
static void Main(string[] args)
{
int[] array = new int[5];
Console.WriteLine("Declare the array size");// 6
int quant = int.Parse(Console.ReadLine());
for (int i = 0; i < quant; i++) {
Console.WriteLine("Fill in the {0}º value ", i+1);
int number = int.Parse(Console.ReadLine());
array[i] = number;
}
for (int i=0; i< quant; i++)
{
Console.WriteLine("\n", array[i]);
}
}
}
You need to create an array specifying the the number of elements after you read the input from the user. what you have done in your code is create an array of int with a size of 5. in case the user write a number larger then 5, you'll get the IndexOutOfRange exception.
class Program
{
static void Main(string[] args)
{
int quant = int.Parse(Console.ReadLine());
int[] array = new int[quant ];
for (int i = 0; i < quant; i++){
Console.WriteLine("Fill in the {0}º value ", i+1);
int number = int.Parse(Console.ReadLine());
array[i] = number;
}
for (int i=0; i< quant; i++){
Console.WriteLine("\n", array[i]);
}
}
}
If you want to use an array without specifing a fixed limit, it's not possible in C# (in JS for instance it is). you can achieve this requirement in C# using a different type called List which represents a strongly typed list of objects that can be accessed by index and does not require specifing a fixed size in initializtion (in contrast to array)
Read more about List - https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0

Exercise in C#,it doesn't work

this is the problem:You are given a sequence of positive integer numbers given as string of numbers separated by a space. Write a program, which calculates their sum. Example: "43 68 9 23 318" -> 461.
That's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercises2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int[] array;
for (i = 0; i < numbers.Length; i++)
{
array = new int[int.Parse(numbers[i])];
int s = Sum(array);
Console.Write("the sum of your numbers is: {0} ", s);
}
}
static int Sum(int[] array)
{
int sum = 0;
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
}
}
I dont know why it doesn't work,is giving me that the sum is 0.
Thank you.
The problem is:
array = new int[int.Parse(numbers[i])];
You actually create array with the length is the given numbers[i]. the array values are all 0. So
int s = Sum(array);
s is always 0.
The correct code is simple:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0, j = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
s += int.Parse(numbers[i]);
}
Console.Write("the sum of your numbers is: {0} ", s);
Console.ReadLine();
}
}
You should only iterate on each element of your array of strings retrieved by .Split and sum.
working example .Net Fiddle:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
Console.WriteLine("Give some numbers");
string n = Console.ReadLine();
int sum = 0;
foreach(var i in n.Split(' ')){
sum += int.Parse(i);
}
Console.Write("the sum of your numbers is: {0} ", sum);
}
}
There is problem with the code where you getting the value of user given array in summation array as initialization of array.
array = new int[int.Parse(numbers[i])];
Here this is in loop array is initialized every time the value is getting. As per your input "43 68 9 23 318". Array will initialize by 43, then 68, then by 9 and so on. When array is initialized the values are by default 0 for int.
So Please refer this solution with proper null and integer check. Hope this will help you!.
static void Main(string[] args)
{
Console.WriteLine("Give some numbers");
int i = 0;
string n = Console.ReadLine();
string[] numbers = n.Split(' ');
if (numbers != null && numbers.Length > 0)
{
int[] array = new int[numbers.Length];
int s = 0;
for (i = 0; i < numbers.Length; i++)
{
// Check if numbers[i] values is integer then add to array for some
int number;
bool result = Int32.TryParse(numbers[i], out number);
if (result)
{
array[i] = number;
}
}
s = Sum(array);
Console.Write("The sum of your numbers is: {0} ", s);
}
Console.Read();
}

How to call function to enter multiple integers into an array?

So the code for the function (Named InsertMark) is below. How would you call this function to enter the marks for say 10 people into an array called iMarks?
static void InsertMark(int [] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
Thanks.
Just move the line piMarkArray[piStuNum] = iMark; inside while loop, use index, and exit the loop if index is not less than array length.
int index=0;
while ((iMark < 0 || iMark > 100) && index < piMarkArray.Length) // exit the loop array is full
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
piMarkArray[index++] = iMark; // Here marks are set
}
//update array element with this mark
Here you create array which will hold 10 marks and fill it with your method in a loop:
int[] marks = new int[10];
for(int i = 0; i < marks.Length; i++)
InsertMark(marks, i);
In main function you could have a code:
int iMarks[10];
for(int i = 0; i <10; i++ )
InsertMark(iMarks, i)
are you looking for something like this?
for(int i=0; i<10; i++)
{
InsertMark(iMarks, i);
}
You need to declare an array of size 10: int[] iMarks = new int[10], then in a for loop pass the array and the counter value through to the function.
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Here is the full class/ working example:
static void Main(string[] args)
{
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Console.Read();
}
static void InsertMark(int[] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while(iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
}
There are always multiple ways to code anything, and this is no exception. What I'm putting here is one example of idiomatic C# to do this. There are at least two variants I can think of which would be better, but this keeps the closest to the original idea.
First, a basic Student class:
class Student
{
public int ID;
public int Mark;
}
Then, a function to prompt for the mark
int GetMark(int studentID)
{
Console.Write("Enter mark for student " + studentID + ": ");
int mark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
return mark;
}
Finally, from your main program, you have a list or array of Student objects called AllStudents and you do:
foreach (Student student in AllStudents)
{
student.Mark = GetMark(student.ID);
}
Alternatively, if you aren't using classes, your loop could be:
int[] marks = new int[10]; // Or whatever size it needs to be.
for (int i = 0; i < marks.Length; i++)
{
marks[i] = GetMark(i);
}

C# Having a dumb Moment when calling method with array

I have this working almost as intended. The program it self is functional but the output is kinda screwy. It requires multiple hits of of the return key in order to display the contents of the array which is in a for loop and being called by the output() method.
=( seems like a simple enough thing but I am not seeing my problem.
My second issue is the fact that I call output(arr) ONCE but the output prints multiple instances of the array based on the size of the array....
class Program
{
static void Main(string[] args)
{
int value;
Console.Write("How big of an Array? ");
int arraySize = int.Parse(Console.ReadLine());
int[] arr = new int[arraySize];
for (int i = 0; i <= arraySize - 1; i++)
{
Console.Write("First Value: ");
value = int.Parse(Console.ReadLine());
arr[i] = Convert.ToInt32(value);
}
output(arr);
Console.ReadLine();
}
static void output(Array arr)
{
foreach (int i in arr)
{
for (int v = 0; v < arr.Length; v++)
{
string number = "Value: ";
string arrayPoint = "Array Section: ";
Console.WriteLine("{0}{1}\t{2}{3}", arrayPoint, v, number, i);
}
}
}
}
Couple of things in your code,
Your output method is receiving parameter of type Array, instead it should be receiving int[], and you should loop it once, not twice.
static void output(int[] arr)
{
for (int v = 0; v < arr.Length; v++)
{
string number = "Value: ";
string arrayPoint = "Array Section: ";
Console.WriteLine("{0}{1}\t{2}{3}", arrayPoint, v, number, arr[v]);
}
}
2nd, in your Main method you are using the prompt Enter First Value, which is somewhat confusing when the user is suppose to enter the value for the 2nd or later elements, you may change it to:
for (int i = 0; i <= arraySize - 1; i++)
{
Console.Write(string.Format("Value for Element {0}: ",i));
value = int.Parse(Console.ReadLine());
//arr[i] = int.Parse(Console.ReadLine()); // or you can do
arr[i] = value;
}
You only need one loop in the output method. Try like this ...
static void output(Array arr)
{
for (int v = 0; v < arr.Length; v++)
{
string number = "Value: ";
string arrayPoint = "Array Section: ";
Console.WriteLine("{0}{1}\t{2}{3}", arrayPoint, v, number, arr.GetValue(v));
}
}

Categories