Why is my for loop stopping before last index? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I want to read 20 items but only 19 are read through console. Any idea why ?
What I'd like my code to do is :
1st : read the interger k from the standard input buffer (console)
2nd : read 20 integers into the array int x[]
static void Main(string[] args)
{
int k ;
int[] x = new int [20];
int[] y = new int [20];
int[] yval = new int[20];
int i;
Console.WriteLine("Enter k value");
k = Console.Read();
Console.WriteLine("Enter x values\n ");
for (i = 0; i <=19 ; i+=1)
{
x[i] = int.Parse(Console.ReadLine());
yval[i] = (x[i] + k) % 26;
}
}

Jon addressed the root of the problem in the comments, but I wanted to try to answer more fully. Console.Read() will only read a single character and return an integer representing the character, probably not what you want. Any characters after that are immediately read on the first pass, probably not what you expected. The issue can be illustrated by inspecting the values:
static void Main(string[] args)
{
int k;
int[] x = new int[20];
int[] y = new int[20];
int[] yval = new int[20];
int i;
Console.WriteLine("Enter k value");
k = Console.Read();
Console.WriteLine("k = {0}", k);
Console.WriteLine("Enter x values\n ");
for (i = 0; i <= 19; i += 1)
{
var input = Console.ReadLine();
x[i] = int.Parse(input);
yval[i] = (x[i] + k) % 26;
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
If you enter "12" for k, the output looks like:
Enter k value
12
k = 49
Enter x values
x[0] = 2
The first character '1' is saved to k as int value of 49 (ASCII value for '1'). The buffer still has a '2' and a newline to be read. They get read on the first pass through the loop and stored in the first element of the array.
As Jon said, you probably want k = int.Parse(Console.ReadLine()); instead.

Related

How can I calculate numbers (for example) from 1 - 10 with the next number. (1+2+3+4+ ...) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Does it have a shorter way than doing something like this:
int[] Summe = new int[6];
Summe[0] = 1;
Summe[1] = 2;
Summe[2] = 3;
Summe[3] = 4;
Summe[4] = 5;
Summe[5] = 6;
Console.WriteLine(Summe[0] + Summe[1] + Summe[2] + Summe[3] + Summe[4] + Summe[5]);
Console.ReadKey();
Using the Enumerable.Sum() method which computes the sum of a sequence of numeric values and Enumerable.Take() which returns a specified number of contiguous elements from the start of a sequence.
Console.WriteLine(Summe.Take(10).Sum());
OR from high school
// sum of integers from 1 to n
int SumNaturalNumbers(int n)
{
return n * (n + 1) / 2;
}
Formula for the general algebraic series starting from a and difference between terms d (Arithmetic progression and series)
sum = n / 2 * (2 * a + (n - 1) * d)
I think using a foreach loop may be helpful here, since you're dealing with an array. Also, you can define your array on one line.
int[] Summe = { 1, 2, 3, 4, 5, 6 };
int total = 0;
foreach (int number in Summe)
{
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
You can simplify this process by simply putting this operation into a while loop.
int i = 0; // tell your program what 'i' should be upon first running the code
while (i < 10) // if 'i' is less than 10, run this block of code. You can change 10 to anything you want
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
This will print each number individually, but you want to calculate the sum of every number, so you could do something like this:
{
public static void Main()
{
int j, sum = 0;
Console.Write("\n\n");
Console.Write("Find the sum of first 10 natural numbers:\n");
Console.Write("----------------------------------------------");
Console.Write("\n\n");
Console.Write("The first 10 natural number are :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j; // add the previous number to the current one
Console.Write("{0} ",j);
}
Console.Write("\nThe Sum is : {0}\n", sum);
}
}
The above code prints the sum of the first 10 natural numbers. I added some additional lines simply to make the program more legible. Again, you can change the number 10 to whatever number you want.

Creating array of elements c# console [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
i just try to make this.
writing a program which create an array of of integer numbers and initializes each the elements with the element's index value, multiplid by five.
print the result
and my code is :..
Console.Title = " Arrays ";
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine(" This Program Is About Partial Automation Array :-");
Console.WriteLine(" ====================================================");
Console.Write("\n Please Enter The Size Of Array : ");
int n = Convert.ToInt32(Console.ReadLine());
int[] arr1 = new int[n];
Console.WriteLine(" =====================================");
// Multible Process :-
for (int i = 0; i < n; i++)
{
arr1[i] = arr1[i] * 5;
}
// Displaying Process :-
Console.WriteLine(" \nThe Result Is :-");
Console.WriteLine(" ================");
for (int i = 0; i < n; i++)
{
Console.Write(" "+ arr1[i] + "\t");
}
Please change arr1[i] = arr1[i] * 5; to arr1[i] = i * 5;
use linq:
const int N = 10;
var array = Enumerable.Range(0, N)
.Select((x, i) => i * 5)
.ToArray();
foreach (var element in array) {
Console.WriteLine($"Value: {element}");
}

Find furthest and closest number to a number in array c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a exercise where I need to find the furthest and closest number to a certain number (average). Can somebody help me? Here is my code:
Console.WriteLine("Geef 10 gehele positieve getallen.");
Console.WriteLine("Getal 1:");
int g1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 2:");
int g2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 3:");
int g3 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 4:");
int g4 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 5:");
int g5 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 6:");
int g6 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 7:");
int g7 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 8:");
int g8 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 9:");
int g9 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 10:");
int g10 = Convert.ToInt32(Console.ReadLine());
int gemiddelde = (g1 + g2 + g3 + g4 + g5 + g6 + g7 + g8 + g9 + g10)/10;
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
If you can use List<int> instead of array it makes things easier to code and probably cleaner depending on who you ask.
let say you change this :
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
Into a list like this :
List<int> values = new List<int>(){g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
An aggregate will test each elements until the list has been completely tested.
So we can try get the closest and furthest value like so
// value you want to check is the average of the list.
// Average is already implemented for the List
var value = values.Average();
// will keep the closest value in the collection to our value we are looking for
// and keep testing with the following value to end up with the final closest
var closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);
// same logic as closest except we keep the furthest
var furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y);
I hope this example can help you even if it is in java.
//Your array with the numbers
int[] data = {12, 123, 65, 23, 4, 213, 32, 342, 21, 15};
int testNum = 27; //Your test value
int holderHigh = testNum;
for(int i = 0; i < data.length; i++){//Goes through the array
//If the holder is lower than a value in the array it will get stored
if(holderHigh < data[i]){
holderHigh = data[i];
}
}
int holderLow = testNum;
for(int k = 0; k < data.length; k++){//Goes through the array
//If the holder is higher than a value in the array it will get stored
if(holderLow > data[k]){
holderLow = data[k];
}
}
System.out.println(holderHigh + " and " + holderLow +
" is the number farthest away from " + testNum);stNum);

Array ints and replace the order of number I write [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I try Start the console and after i write 5 numbers is do exsepsion what wrong in code
what the console do is after I write 5 number for example 7,4,9,5,1 ---> 1,5,9,4,7
this what I wrote
static void Main(string[] args)
{
int[] numbers = new int[5];
for (int i = 0; i < numbers.Length ; i++)
{
Console.Write("");
numbers[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < numbers.Length / 2; i++)
{
int x = numbers[i];
numbers[i] = numbers[numbers.Length - i - 1];
numbers[numbers.Length - i - 1] = x;
}
Console.Read();
You missed two things. First - in order to swap two array items, you need to store item somewhere. Otherwise you just replace one item with other. Second - arrays have indexes from 0 to Length - 1. So you need to subtract 1 from second item index:
for (int i = 0; i < numbers.Length / 2; i++)
{
int x = numbers[i];
numbers[i] = numbers[numbers.Length - i - 1];
numbers[numbers.Length - i - 1] = x;
}

Find numbers that don't divide by 3 or 7 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I need help with a program.
I need to write a program that prints on the console numbers from 1 to N that can't divide in the same time by 3 or 7. I need to parse N so the user inputs a value for it. Here is my code for now, can you tell me what is wrong?
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
for (n = 1; n <= 99999; n++) {
//n % (3 * 7) == 0
I thought out how I will check it but I can't think out how to make the other part. I think there is something wrong with my loop too. Can you give me some hints where I am mistaken and what I can do? Thank you!
You're getting N from the user then immediately overwriting it. Use a different variable for your loop:
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
// do stuff
You can use Modulus %
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int n;
if (int.TryParse(input, out n))
{
for (int i = 1; i < n; i++)
{
if(i % 3 != 0 || i% 7!= 0) Console.WriteLine(i);
}
}
Your loop is wrong because your condition is wrong.It should be i < n, you are getting an input but then you overwriting it's value by n = 1;
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
if (i % 21 != 0) { Console.Write(i + " "); }
}
Example: http://ideone.com/ThASen

Categories

Resources