I need to create an application that fills an array with random numbers. I written the whole code and it works but the numbers are not displaying in the console window. What could be wrong with the code? Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Arrays
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
Random randomNumbers = new Random();
for (int i = 0; i < array.Length; i++)
{
int randomValue = randomNumbers.Next(0,500);
array[i] = randomValue;
}
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("The array value is: ", array[i]);
}
}
}
}
You can either use
Console.WriteLine("The array value is: {0}", array[i]);
or
Console.WriteLine("The array value is: " + array[i]);
but what you wrote,
Console.WriteLine("The array value is: ", array[i]);
entirely misses on telling the console where and how you use the array[i] variable.
Console.WriteLine("The array value is: {0}", array[i]);
You have to indicate in the format string that you want to print some value.
//Console.WriteLine("The array value is: ", array[i]);
Console.WriteLine("The array value is: {0}", array[i]);
Console.WriteLine("The array value is: {0}", array[i]);
You are missing
Console.ReadLine();
After Console.WriteLine();
As others have mentioned, to get this line to work with {0}, you'd need to format it as a string,
Console.WriteLine(string.Format("The array value is: {0}", array[i]));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Coefficient Of x (Positive): ");
int coef = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Value Of c: ");
int c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("From? (Positive)");
int from = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("To? (Positive)");
int to = Convert.ToInt32(Console.ReadLine());
Console.Clear();
int[] y_val = new int[(to - from) + 1];
int counter = 0;
for (int i = to; i >= from; i--)
{
y_val[counter] = ((coef * i) + c);
counter++;
}
int x = 0;
for (int i = to; i >= from; i--)
{
if (y_val[x] == ((coef * i) + c))
{
if (y_val[x] >= 10)
{
Console.WriteLine("{0}|", y_val[x]);
}
else
{
Console.WriteLine("0{0}|", y_val[x]);
}
for (int j = 0; j < i; j++)
{
Console.Write(" ");
}
Console.Write("*");
Console.WriteLine();
}
x++;
}
Console.WriteLine("______________________________________________________________");
Console.WriteLine("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23");
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("asd");
}
}
}
Related
So, I've made a program that is supposed to collect the amount of numbers you put in and then count them backwards.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace K4_Labb_3
{
class Program
{
static void Main(string[] args)
{
Console.Write("Ange antalet heltal du vill lagra i fältet: ");
int heltal = int.Parse(Console.ReadLine());
int[] i = new int[heltal];
Console.WriteLine("Ange " + heltal + " heltal: ");
for (int j = 0; j < i.Length; j++)
{
int o = int.Parse(Console.ReadLine());
i[j] = o;
}
Console.WriteLine("Talen utskrivna baklänges: " );
for (int l = i.Length; l > 0; l--)
{
Console.Write(i[l]);
}
}
}
}
But I am getting the error "index was outside the bounds of the array" and I was wondering if anyone could help me out, and explain what was wrong.
Problem here:
for (int l = i.Length; l > 0; l--)
When you have an array of length say LEN, then you can only access elements with index 0, 1, 2, ..., LEN-1.
While printing the array, you were you were starting from one place more than the limit. If the lenght is 5, then the array places will be 0,1,2,3,4.
But in your program while printing you were starting from 5, which was throwing the error and which is correct.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.Write("Ange antalet heltal du vill lagra i fältet: ");
int heltal = int.Parse(Console.ReadLine());
int[] i = new int[heltal];
Console.WriteLine("Ange " + heltal + " heltal: ");
for (int j = 0; j < i.Length; j++)
{
int o = int.Parse(Console.ReadLine());
i[j] = o;
}
Console.WriteLine("Talen utskrivna baklänges: ");
for (int l = i.Length-1; l >= 0; l--)
{
Console.Write(i[l]);
}
}
}
}
I was given an assignment in my programming class with a prompt that directly reads,
"In this exercise exam scores for a class of students is stored in a file. You are to write a program that successfully opens the file, reads in the exam scores, and outputs them on the console."
Every time I run my program an error occurs showing that,
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in GradeCalculator.exe"
The error appears on the code, "gradesArray[i] = gradesArray[gradeData];
i++;"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
while (!grades.EndOfStream)
{
for (int i = 0; i != 50;)
{
gradeData = int.Parse(grades.ReadLine());
gradesArray[i] = gradesArray[gradeData];
i++;
}
}
Program calc = new Program();
for (int i = 0; i < 50; i++)
{
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
}
public int averageArr(int[] arr)
{
int avg = 0;
int numGrades = 0;
int sum = 0;
for (int i = 0; i < 50; i++)
{
do
{
sum += arr[i];
} while (arr[i] != 0);
}
avg = sum / numGrades;
return avg;
}
}
}
Any suggestions on how to fix this?
Data from file:
88
90
78
65
50
83
75
23
60
94
EDITED NEW CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\grades.txt";
int gradeData;
StreamReader grades = new StreamReader(folder);
int[] gradesArray = new int[50];
do
{
gradeData = int.Parse(grades.ReadLine());
for (int i = 0; i != gradesArray.Length;)
{
gradesArray[i] = gradeData;
i++;
}
}
while (!grades.EndOfStream);
Program calc = new Program();
int average = calc.averageArr(gradesArray);
Console.WriteLine("{0}", average);
Console.ReadLine();
}
public int averageArr(int[] arr)
{
int avg = 0;
int sum = 0;
for (int i = 0; i != arr.Length; )
{
sum += arr[i];
i++;
}
avg = sum / arr.Length;
return avg;
}
}
}
You have lot of redundant code, you simply could use Linq and get an array of int.
var intArray = File.ReadAllLines("filepath")
// Remove below line if you have only 1 number in each line, else specify delimiter and keep it.
.SelectMany(s=>s.Split(' '))
.Select(int.Parse);
Once you get the array, Array has function which returns Average
var average = intArray.Average();
Update:
Since you want to write function that calculates average, you could do this. Please note I modified few variable types to Decimal to avoid intdivision.
public decimal averageArr(int[] arr)
{
decimal avg = 0;
int numGrades = 0;
decimal sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
avg = sum / arr.Length;
return avg;
}
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();
}
I am absolutely new to C# and I am at total lost. What I need to do is enter numbers as many as possible and keep entering but when you enter the value "0" that is when you add all the entered numbers all up.
This is my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
Console.WriteLine("The sum is: " + n);
}
Console.ReadLine();
}
}
}
Some advices:
The while loop is a better practice than the do..while loop.
You should use the int.TryParse method for input validation.
You should calculate sum of numbers inside loop.
You can solve the problem with only two int variables: n for readed numbers and sum for numbers sum.
For example, you can solve your problem with the following code:
static void Main(string[] args)
{
int sum = 0;
while (true)
{
Console.WriteLine("Enter a Number: ");
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
if (n == 0)
break;
sum += n;
}
}
Console.WriteLine("The sum is: " + sum);
}
you can simply do that with do ... while ... loop.
private static void Main(string[] args)
{
int n, sum = 0;
do
{
Console.WriteLine("Enter a number:");
n = Convert.ToInt32(Console.ReadLine());
sum += n;
} while (n != 0);
Console.WriteLine("Sum is:"+sum);
Console.ReadKey();
}
ConvertToInt32() is a method for converting a string to int32 (int).
You print the sum outside while loop.
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activity2
{
class Program
{
static void Main(string[] args)
{
int n, sum, x = 0;
do
{
Console.WriteLine("Enter a Number: ");
n = int.Parse(Console.ReadLine());
}
while (n != 0);
{
sum = n + x;
x = n;
n = sum;
}
Console.WriteLine("The sum is: " + n);
Console.ReadLine();
}
}
}
Here i am pasting the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace star1
{
class Program
{
static void Main(string[] args)
{
Myclass obj = new Myclass();
obj.getData();
obj.pattern();
}
}
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
}
Looks like you're redeclaring n as a local variable in getData().
Try changing that line to:
n = Convert.ToInt32(Console.ReadLine());
i.e. remove the int.
well ...
as you are not using this...
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
this.n = Convert.ToInt32(Console.ReadLine());
// OR
//n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
i would encourage you to use this to distinct between scope- and instance-variables!
If you try to assign n using Console.ReadLine() in getData(), you need to remove the "int" just before. Currently, you have 2 "n" variable in different scopes. That's why your loop doesn't work.