Exercise in C#,it doesn't work - c#

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();
}

Related

How to count number of 1s without using an array?

static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
int[] a = new int[m];
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1s in the Entered Number : "+count);
Console.ReadLine();
}
here get each value into the array, and check each value equal to one are not. But i need this task without using an array. Could you please help us.
Just check the input when it's entered, without storing it:
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
if(Console.ReadLine() == "1")
count++;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();
}
You can simply keep a count where you add it to the array
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
count += Console.ReadLine() == "1" ? 1 : 0;
}
Console.WriteLine("Number of 1's in the Entered Number : "+count);
Console.ReadLine();
You could use LINQ and remove the for loop as well as the array.
Console.WriteLine("Enter the Limit : ");
int m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the Numbers :");
int count =
Enumerable
.Range(0, m)
.Select(n => Console.ReadLine())
.Where(x => x == "1")
.Count();
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();
I would advice using more meaningful variable names and adding input validation Int32.TryParse instead Convert.ToInt32.
Just do the if (o == 1) check in the first for and forget about the second one.
You can use List instead of array.
code is here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberofOnes
{
public class Program
{
static void Main(string[] args)
{
int m, count = 0;
Console.WriteLine("Enter the Limit : ");
m = int.Parse(Console.ReadLine());
List<int> a = new List<int>();
Console.WriteLine("Enter the Numbers :");
for (int i = 0; i < m; i++)
{
a.Add( Convert.ToInt32(Console.ReadLine()));
}
foreach (int o in a)
{
if (o == 1)
{
count++;
}
}
Console.WriteLine("Number of 1's in the Entered Number : " + count);
Console.ReadLine();
}
}
}

Error with program that opens file, reads data, and calculates the average

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;
}

Adding the sum of the entered numbers when you enter 0 in C#?

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();
}
}
}

Array duplicate deletion in C#

This is my code so far I have display all items in the array as the user enters and create an error message for duplicate numbers that deletes the duplicate and continues the loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace midterm
{
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("How many numbers will you enter?");
size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
int i;
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i != j)
{
if (numbers[j] == numbers[i])
{
int k = j;
while (k < size - 1)
{
numbers[k] = numbers[k + 1];
k++;
}
size--;
}
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < size; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
}
Every time I go to change the for loops around or add an error message then the program stops deleting the duplicates I am really stumped on this one can someone lend me a hand.
Have a look at LINQ, it has some great functions that can be used for collection manipulation. In your situation I would do the following:
Distinct() here filters the array to only unique values.
int[] initialArray = new int[] { 1, 1, 2, 3, 4, 5 };
int[] noDuplicates = initialArray.Distinct().ToArray(); // [1,2,3,4,5]
I would recommend using a List instead of array. A List will allow you to keep adding entries to it without having to specify the size.
With the list, you can check if entry exists already before adding it, so you wont have to remove or delete
Easy way, use a HashSet
HashSet<int> mySet = new HashSet<int>();
//...
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (!mySet.Add(number))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
}
If you must use arrays:
for (i = 0; i < size; i++)
{
Console.WriteLine("Enter number: ");
int numbers = Convert.ToInt32(Console.ReadLine());
if (ExistsInArray(number, numbers))
{
Console.WriteLine("That was a duplicate. Try again");
i--;
}
else
{
numbers[i] = number;
}
}
And then:
private static bool ExistsInArray(number, numbers)
{
// Your code to search numbers for number and return true if found
// Left as an exercise for the OP
}
One important note here is that it's a lot easier to check whether your array already contains the element you are trying to add than to remove it after the fact. If it already exists, just don't add it again.

Whats wrong with my C# program?

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");
}
}
}

Categories