Simple program not working - c#

this is the first time i work on C# and ASP.NET, i'm reading Beginning ASP.NET 4 in c# 2010 but i never worked with object-oriented programming. (I'm a network admin so i know basic programming).
Still, i can't get to work a simple program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
int i;
string[] nomi = new string[7];
string[] cognomi = new string[7];
for (i = 0; i = 6; i++) {
Console.WriteLine("Inserisci il", i + 1, "° nome");
nomi[i] = (Console.ReadLine);
}
for (i = 0; i = 6; i++) {
Console.WriteLine("Inserisci il", i + 1, "° cognome");
nomi[i] = (Console.ReadLine);
}
for (i = 0; i = 6; i++) {
Console.WriteLine(nomi[i], " ", cognomi[i]);
}
}
}
}
The problem is not in the algorythm but in the declaration part. I can't show the error log because i have VS in Italian.
Where am i wrong?

It's tough to help without error messages (maybe you can translate them since you obviously know both languages).
For sure, your for loop syntax is incorrect. This:
for (i = 0; i = 6; i++)
Should be:
for (i = 0; i < 6; i++) // Or <=, or whatever
Take a look at for loop documentation on MSDN.
In addition Console.ReadLine is a method, not a property:
nomi[i] = Console.ReadLine();

Your for loops are incorrect. They should be
for (int i = 0; i < 7; i++)
{
}
Or, better,
for (int i = 0; i < nomi.Length; i++)
{
}
What this is saying is that i should start at 0, continue looping until the value if i is no longer less than 7 (or the value of nomi.Length) and i should increase by 1 each loop (i++).
Also, unrelated to the loops, it should be Console.ReadLine();. The () shows that it's a method that takes no parameters, whereas nomi.Length does not have () because it is a property, not a method.
Your arrays also need to be static.
static string[] nomi = new string[7];
static string[] cognomi = new string[7];
Just to clarify, you don't always need to use static when declaring variables. The reason you need it here is because you're calling them from within a static method (static void Main(string[] args)).
Edit - As mentioned in the comments, this assumes that the variables are being declated outside the Main method which is resulting in the error An object reference is required for the nonstatic field, method, or property 'member'. If they are not, then these variables do not have to be static.

Your for loops don't make any sense for (i = 0; i = 6; i++)
The syntax is for (initialization, condition, iteration)
Right now your condition is an assignment, so it is always going to be true. I think you wanted it to be for (i = 0; i **<** 6; i++)

When writing for loops you should always make a int variable in the scope of the declaration of the for loop
Example:
for (int i = 0; i < 10; i++)
{
body code goes here
}
There integer should be declared and disappear within the scope of the loop.
Hope that helps

I corrected your for and Console.WriteLine syntax and made your code more readable. This should be able to guide you.
const int length = 7;
string[] nomi = new string[length];
string[] cognomi = new string[length];
for (int i = 0; i < length; i++)
{
Console.WriteLine("Inserisci il {0} ° nome", i + 1);
nomi[i] = (Console.ReadLine());
}
for (int i = 0; i < length; i++)
{
Console.WriteLine("Inserisci il {0} ° cognome", i + 1);
cognomi[i] = (Console.ReadLine());
}
for (int i = 0; i < length; i++)
{
Console.WriteLine("nomi: {0} cogomi: {1}", nomi[i], cognomi[i]);
}

Related

String array to int array conversion

I have a problem with converting string array (previously loaded from .txt file) to integer one. File has got 100 random numbers, they load without any problem, I just need to convert them to integers to make them sortable with 3 types of sorting. I've tried many thing that were said here, but none of them seem to work. All the time I'm getting an error saying that it can't be converted.
Here is my loading from the file code:
string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
int[] numb= new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
And after some options to choose I'm using switch to pick one:
switch (a)
{
case 1:
Console.WriteLine("1. Bubble.");
//int[] tab = numb;
babel(path);
for (int z = 0; z < path.Length; z++)
{
Console.Write(path[z] + ", ");
}
break;
I've got bubble sorting method in my program too, don't think it is necessary to post it here.
If anyone can help me here, I'd be really grateful.
#Amy - I've tried this:
numb[i] = path[i].Convert.toInt32(); - it doesn't work.
What I want to achieve is to change every number in this array to int, I think it should be involved here:
{
Console.WriteLine(path[i]);
}
This conversion works.
#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Length; i++)
{
Console.WriteLine(numb[i]);
}
It is better to use TryParse instead of parse. Also it is easier to work with List, than with array.
using System;
using System.Collections.Generic;
namespace StringToInt
{
class Program
{
static void Main(string[] args)
{
String[] path = { "1", "2", "3", "a", "b7" };
List<int> numb = new List<int>();
foreach (string p in path)
{
if (int.TryParse(p, out int result))
{
numb.Add(result);
}
}
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Count; i++)
{
Console.WriteLine(numb[i]);
}
}
}
}
I can't imagine this wouldn't work:
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
I think your issue is that you are using File.ReadLines, which reads each line into a single string. Strings have no such ToArray function.

How to iterate numbers to a limit by addition

Here is the code I have right now:
for(int i=0; i< 35; ++i)
{
int a = 1;
a+=1;
Console.WriteLine(a);
}
The output is:
2
2
2
...
and so on, until the loop terminates.
What I want to do is add the previous two numbers to make the nest number then so on all the way to 34.
This is how you can achieve what you want:
//Initializing the elements
int a = 0;
int b = 1;
int c = 1;
Console.WriteLine(a); //Typing the 0'th element
Console.WriteLine(b); //Typing the first element
for(;c <= 34; c = a + b) {
Console.WriteLine(c); //Typing the actual element
a = b;
b = c;
}
You mean count to some number by adding other and using this as what? Escape condition? Just as a constant in addition?
as escape condition:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
public static void Main()
{
for (i = 0; i < 100; i++){
a += i;
if (a == 595) break;
}
Console.WriteLine(i);
}
}
as a constant in addition:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
static private int d = 1;
public static void Main()
{
for (i = 0; i < 34; i++){
a += d;
}
Console.WriteLine(a);
}
}
Both seem highly illogical to use tho :/
EDIT: Your question is now different from what you told before :D
You are wondering why is a not getting larger than 2? Because you initialize it each step of for loop. You need to move initialization out of the scope of for. Try this:
using System;
public class Program
{
static private int a = 0;
static private int i = 0;
static private int d = 1;
public static void Main()
{
int a = 1;
for(int i=0; i< 34; ++i)
{
Console.WriteLine(a);
a+=1;
}
}
}
I understand you need numbers from 1 to 34. So you can't start with 1, immediately increment by 1 and then write it cause it will be 2. Write first, then increment.
Or you can start with 0 then you can increment first. But adjust end condition as well.
You are declaring a new variable a with each iteration and then add 1 to it. Since the initial value of a is 1, you calculate 1+1 with each iteration. Step through the code in a debugger to see what I mean.
Move the declaration out of the loop and you should see your desired output:
int a = 1;
for(int i=0; i< 35; ++i)
{
a+=1;
Console.WriteLine(a);
}
There are tons of tutorials how you can print out the fibonacci sequence, for example with two nested for-loops:
for (int i = 0; i < 10; ++i)
{
int a = 0;
int b = 1;
for (int j = 0; j < i; ++j)
{
var temp = a;
a = b;
b = temp + b;
}
Console.WriteLine(a);
}
Example taken from dotnetperls (albeit slightly edited by me).

C# Transcribing data to the second table and reversing them

I am will be grateful for help because I am not sure how make this program.
I should code program with two tables. The first will fill it with numbers Random tab = new Random();. After that I should reverse numbers and fill them into second table.
I made first functionality but I am not sure how make start with second table?
class Program
{
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine("Tablica wylosowała nastepujace elementy:");
Console.WriteLine(tablica1[i]);
}
Console.Read();
int[] tablica2 = new int[20];
/*for (int i = 20; i > 0; i--)
{
}
*/
}
}
You didn't quite describe what exactly happens when you run the code, but I think the problem is with this part - as this should give you an IndexOutOfRangeException:
for (int j = tablica2.Length; j > 1 ; j--)
{
tablica2[j] = tablica1[20-j];
Console.WriteLine(tablica2[j]);
}
The array indices go form 0 to tablica2.Length - 1 (one less then the length, so the index tablica2.Length is outside the array).
Your loop goes in reverse from tablica2.Length two 2 for some reason.
So as soon as it starts executing, j is 20, but the highest index is 19.
Change the loop so it goes the full range, and change the loop body so that you don't access out-of-range indices, in one of two ways:
for (int j = tablica2.Length - 1; j >= 0 ; j--) // goes from 19 to 0
{
tablica2[j] = tablica1[tablica1.Length - j - 1];
}
or
for (int j = tablica2.Length; j > 0 ; j--) // goes from 20 to 1
{
tablica2[j - 1] = tablica1[tablica1.Length - j];
}
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine("Tablica wylosowała nastepujace elementy:");
Console.WriteLine(tablica1[i]);
}
Console.Read();
int[] tablica2 = new int[20];
for (int i = 20; i > 0; i--)
{
tablica2[i]=tablica1[20-i];
}
}
}
#Sinatr Thank You for this topic. It was really helpful but there is only one table.
#Filip Milovanović Yes, I have to make two two tables :) After reserving first, I should put elements from first to second. I changed this for, but in console I am still able to see only first one. :(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Randomy1
{
class Program
{
static void Main(string[] args)
{
int[] tablica1 = new int[20];
Random tab = new Random();
for (int i = 0; i < 20; i++)
{
tablica1[i] = tab.Next(20);
Console.WriteLine(tablica1[i]);
}
int[] tablica2 = new int[20];
for (int j = tablica2.Length; j > 1 ; j--)
{
tablica2[j] = tablica1[20-j];
Console.WriteLine(tablica2[j]);
}
Console.Read();
}
}
}
I think this would work
for (int i = 0; i < 20; i++)
{
tablica2[i] = tablica1[20 - (i + 1)];
Console.WriteLine("Tablica 1st :: " + tablica1[i] + " Tablica 1 Reverse " + tablica1[20 - (i + 1)] + " Tablica 2 " + tablica2[i]);
}

Selection Sort Implementation

I'm not really sure what's wrong with the implementation I have. How would I fix this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectionSort
{
class Program
{
static void algorithm(int[] to_sort)
{
int bufor;
for (int i = 0; i < to_sort.Length; i++)
{
for (int j = i + 1; j < to_sort.Length; j++)
{
if (to_sort[i] >= to_sort[j])
{
bufor = to_sort[i];
to_sort[i] = to_sort[j];
to_sort[j] = bufor;
}
}
}
}
static void Main(string[] args)
{
int[] to_sort = new int[100];
Console.WriteLine("");
for (int i = 1; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.WriteLine("");
algorithm(to_sort);
Console.WriteLine("\n");
Console.WriteLine("Sorted list:");
for (int i = 0; i < 100; i++)
{
Console.Write(to_sort[i] + " ");
}
Console.Read();
}
}
}
This produces the following output:
Original list: 00000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
Sorted list: 000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000
It looks like my array (int[] to_sort) was empty, am I right? How can I get this:
Original list: 123456789....100
Sorted list: 123456789...100
Perhaps you originate from the C++ world where initializing an array does not mean the array is "cleaned" (the data that happened to be located at the allocated memory remains untouched), but in C# if you initialize an array like:
int[] to_sort = new int[100];
It means you construct an array where every element is set to default(T) with T the type. For an int that is 0 (for objects it is null, etc.). So you just constructed an array filled with zeros.
You can however for instance fill it with random numbers like:
Random rand = new Random();
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = rand.Next(0,1000);
}
EDIT
Based on your comment, you want to fill it with the positions, you can do this like:
for(int i = 0; i < to_sort.Length; i++) {
to_sort[i] = i+1;
}
I think the easiest and shortest way you can initialize an array of sequential numbers is like this:
int[] to_sort = Enumerable.Range(1, 100).ToArray();
What you have will just allocate the array and fill it with the default value for int, which is 0:
int[] to_sort = new int[100];

Threading modifying unintended variable [duplicate]

This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 9 years ago.
I'm fairly new to C# threading, so apologies in advance for this newbie error. The aim of the following code is to evaluate the fitness of a population that is stored in an array called members. The procedure members.calculateFitness() is a black box (i.e. I can't modify it to improve performance), so I'm trying to setup threads that call the black box simultaneously, and each thread will deal with 1/THREAD_COUNT population members (so if THREAD_COUNT=4, each thread will deal with 1/4 of the population).
In the first for loop I initialise each thread. In the second for loop, I start the thread.
public void ThreadedPrintPopFitness ()
{
int THREAD_COUNT = 1;
int membersPerThread = members.Length / THREAD_COUNT;
Thread[] fitnessCalculator = new Thread[THREAD_COUNT];
int[] threadResult = new int[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
int start = i * membersPerThread;
int stop = (i+1) * membersPerThread;
fitnessCalculator [i] = new Thread (() => getMaxFitness (members, start, stop, ref threadResult [i]));
}
for (int i = 0; i < THREAD_COUNT; i++) {
fitnessCalculator [i].Start ();
}
for (int i = 0; i < THREAD_COUNT; i++) {
fitnessCalculator [i].Join ();
}
int maxFitness = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
if (maxFitness < threadResult [i])
maxFitness = threadResult [i];
}
Console.WriteLine ("(ThreadedCount) Fittest Population Member's Fitness: " + maxFitness);
}
private static void getMaxFitness (PopulationMember[] members, int start, int stop, ref int result)
{
int maxFitness = 0;
for (int i = start; i < stop && i < members.Length; i++) {
if (members [i].calculateFitness () > maxFitness) {
maxFitness = members [i].lastFitness;
}
}
result = maxFitness;
}
Stepping through the code shows that it gets into the second for loop, and then jumps back to the first for loop and declares an IndexOutOfBoundsException on the integer i. I can see that i = THREAD_COUNT (I've tried with different numbers for THREAD_COUNT).
I'm completely baffled, what am I doing wrong?
Thanks in advance!
Servy has it spot on, I even remember reading about this in John Skeet's book now. I had to make a copy of i within the for loop, this fixed it.
Thanks!
As written in the comments, i is captured, and when increased, the function refers to the new value.
What you should do is copy its value to a local variable:
for (int i = 0; i < THREAD_COUNT; i++) {
int start = i * membersPerThread;
int stop = (i+1) * membersPerThread;
int resultId = i;
fitnessCalculator [i] = new Thread (() => getMaxFitness (members, start, stop, ref threadResult [resultId]));
}

Categories