C# for loop error > is invalid [closed] - c#

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 7 years ago.
Improve this question
I am trying to make a prime number generator.
I get three errors:
<21,22> expected >
<21,23> expression > is invalid
<21,24> expected ;
translated errors from norwegian. they may not be exact
using System;
namespace Primtall
{
class Program
{
static void Main(string[] args)
{
Generator G = new Generator();
G.gen();
}
}
public class Generator
{
int a = 0;
int divident = 0;
public void gen()
{
for (a; a<100; a++;)
{
for (divident; divident <= 50;divident++)
{
int div = a/divident;
if((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}
}

There is no need to define a and divident variables as fields. You make no use of them except in the loop. In fact, using class members (fields) as loop variables will immediately render your class as "not thread safe", becuase if two seperate threads execute the gen() method on the same Generator instance they will both fail to get correct results
Change your Generator class like this: (divident starting from 1 to avoid divide by zero exception)
public class Generator
{
public void gen()
{
for (int a = 0; a < 100; a++)
{
for (int divident = 1; divident <= 50; divident++)
{
int div = a / divident;
if ((div % 1) == 0)
{
Console.WriteLine(a);
}
else
{
break;
}
}
}
}
}

You declare variables before loops, so you must leave empty first argument in for:
for (; a < 100; a++)
{
for (; divident <= 50; divident++)
{
Or better declare loop variables in loop:
for (var a = 0; a < 100; a++)
{
for (var divident = 2; divident <= a / 2; divident++)
{
Also, you have some problems in algorithm:
int div = a/divident;
if((div % 1) == 0)
Should be replaced with:
if((a % divident) == 0)
{
flag = false;
break;
}
Declare flag in first loop as true and check it after second loop finish. If it's stil true - number is prime. Also, start second loop with 2 and end with a / 2

You seem to be misunderstanding how for loops work
for(Initialise; While; Action)
so in english what you are asking it to do is
for
a where a starts at 0
while a less than 100
perform body
then increment a by 1
this in code is
For(int a = 0;a<100;a++)
{
//body
}

Related

How to find a way of output the number of attempts for each question of the quiz?

I am making the quiz application on C# in Console version. I have almost done all things, but I don't know how to show the number of attempts for each question, after when the quiz is finished. If you know something, let me know.
I can not add more lines of the code, as the website doesn't allow to do it
if (keys[index] == answer) // Answer is correct
{
Console.WriteLine();
Console.WriteLine("Congratulations. That's correct!");
Console.WriteLine();
totalScore += markPerQuestion;
index++;
Console.WriteLine("The total score is: {0}", totalScore);
Console.WriteLine("Used attempt(s): {0}", attempt);
attempt = 1;
count = attempt;
markPerQuestion = 20;
}
else // Answer is incorrect
{
attempt++;
count++;
if (attempt <= 3)
{
markPerQuestion /= 2;
}
else if (attempt > 3 && attempt < 5) // The fourth attempt gives zero points
{
markPerQuestion = 0;
totalScore += markPerQuestion;
}
else if(attempt >= 5) // Move to the next question
{
Console.WriteLine("Sorry, you used all attempts for that question. Moving to the next question");
index++;
markPerQuestion = 20;
attempt = 1;
count = attempt;
continue;
}
Console.WriteLine("Oops, try again");
}
if ((index > keys.Length - 1 && index > questions.Length - 1)) // Questions and answer keys are finished
{
for (int i = 0; i < questions.Length; i++)
{
Console.WriteLine("Question {0} was answered after {1} attempt(s)", (i + 1), count);
}
break;
}
Consider this solution:
Create a public class that will allow you to store the results.
public class QuizMark
{
public int Attempts;
public int Mark;
}
For the Console app create a method to control the Quiz. Call the method Quiz() from the Main method.
private const int MAX_ATTEMPTS = 5;
private static void Quiz()
{
var quizResults = new List<QuizMark>();
var questionAnswers = new List<int>() { 1, 3, 5, 2, 3, 6 };
foreach(var a in questionAnswers)
{
var v = QuizQuestion(a);
quizResults.Add(v);
}
int i = 0;
quizResults.ForEach(e => Console.WriteLine($"Question: {++i} Attempts: {e.Attempts} Mark: {e.Mark}"));
var total = quizResults.Sum(s => s.Mark);
Console.WriteLine($"Total Points: {total}");
}
Notice the List collection that stores an object of the class QuizMark. This is where the results of each question are stored: attempts and points.
The List questionAnswers simply contains the expected answer to each of the questions.
Now create the method that is going to control how each question in the quiz will be handled:
private static QuizMark QuizQuestion(int answer)
{
var quizMark = new QuizMark();
int guess = 0; //Store ReadLine in this variable
int mark = 20;
for (int attempt = 1; attempt < MAX_ATTEMPTS + 1; attempt++)
{
guess++; //remove when adding Console.ReadLine
if (guess.Equals(answer))
{
quizMark.Attempts = attempt;
quizMark.Mark = mark;
break;
}
else
{
mark = attempt <= 3 ? mark/2 : 0;
quizMark.Attempts = attempt;
quizMark.Mark = mark;
}
}
return quizMark;
}
You will need to replace the incrementor guess++ with the actual guess the user makes. This code is designed to go though automatically just as a demonstration.
IMPORTANT NOTE:
You will want to do some error handling any time you allow users to enter data. They might enter non-integer values. Probably using a loop around a Console.ReadLine where you check the value of the input with a Int32.TryParse().

Return all powers of 2 less then n in C# [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 2 years ago.
Improve this question
For a given number n, I need to return all powers of 2 less than n, as a string in a way that elements are separated with "-". If n < 2, it needs to return an empty string.
For example:
n = 20 => 1-2-4-8-16
n = 8 => 1-2-4
I'm a beginner, so any help would be much appreciated! :)
EDIT: this is not working
using System;
class N
{
static int[] powerof2(int n)
{
int[] array = new int[n];
if (n < 2)
return new int[0];
for (int i = 0; i < 8 * sizeof(uint); i++)
{
int curr = 1 << i;
if (curr > n)
break;
array[i] = curr;
}
return array;
public override string ToString()
{
for (int i = 0; i < array.length; i++)
return (array[i] + "-");
}
}
static public void Main ()
{
int n = 10;
Console.WriteLine(powerof2(n).ToString());
}
}
You need to run the for loop with the following rule
for (int i = 1; i < n; i *= 2)
Whole solution
class Program
{
static void powerof2(int n)
{
if (n < 2)
Console.WriteLine(string.Empty);
for (int i = 1; i < n; i *= 2)
{
if (i > 1)
Console.Write("-");
Console.Write(i);
}
}
static void Main(string[] args)
{
powerof2(20);
}
Using iterator methods makes this case trivial (Fiddle):
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int> GetPowersOf2(int maxN)
{
for (int p = 1; p < maxN; p *= 2)
{
yield return p;
}
}
public static void Main(string[] args)
{
IEnumerable<int> powersOf2LessThan20 = GetPowersOf2(20);
Console.WriteLine(string.Join("-", powersOf2LessThan20));
}
}
I suppose this is what you're looking for:
class Program
{
public static string Pow2LessThan(ulong n)
{
if (n < 2)
return "";
// start with 2^0
string res = "1";
// try further
int p = 1;
ulong cnum = 2;
while (cnum < n)
{
res += "-" + cnum.ToString();
++p;
cnum = (ulong)(1 << p);
}
return res;
}
static void Main(string[] args)
{
ulong n = 20;
Console.WriteLine(Pow2LessThan(n));
Console.ReadLine();
}
}
The reason that it's not working is: you never access the class N in any way. The call should be
Console.WriteLine(N.powerof2(n).ToString());
^^
With that modification, you'll be notified that the method powerof2() is inaccessible due to its protection level. You need to make it at least internal like so:
internal static int[] powerof2(int n)
Next, note that you're missing a } for that method.
return array;
}
With that fixed, the compiler will tell you that you can't access array inside ToString(), because the scope of array is limited to powerof2(). Make the array a field of the class like
static int[] array;
Now, the compiler complains about array.length in ToString(). Fix that by capitalizing Length.
Mistake number 6: ToString() will return in the first iteration of the loop. It will not return anything if array.Length is 0. The function should look a little bit like this:
public override string ToString()
{
string result = "";
for (int i = 0; i < array.Length; i++)
result += array[i] + "-";
return result;
}
Now, this will still not work, because the main method calls ToString() on the return value of powerof2(), which is of type int[] and not of type N. That's because your stuff is static. Make it non-static instead and create an instance of N.
static public void Main ()
{
var n = new N();
n.powerof2(10);
Console.WriteLine(n.ToString());
}
With 7 issues fixed, the output is now 1-2-4-8-0-0-0-0-0-0-, so there's still stuff to fix. Maybe you get a little bit of a feeling why everyone proposes a totally different solution.
What else to fix:
the output of course is still incorrect.
if someone inputs 4000000000 as the number, you certainly don't want to allocate 4 GB of RAM in the array.
Why allocate an array at all and not construct the string right away?
Why 8*sizeof(uint)? You can't shift more often than sizeof(uint).
class Program
{
static string powerof2(int n)
{
var str="1" ;
if (n < 2)
return "" ;
else
{
var i=1;
while(Math.Pow(i, 2)<n)
{
str+="-" +Math.Pow(2, i);
i++;
}
return str;
}
}
static void Main(string[] args)
{
powerof2(50);
}
}

sort way to find prime number but it have some error#? [duplicate]

This question already has answers here:
Program to find prime numbers
(28 answers)
Closed 6 years ago.
i try to find prime number by use that code:
public static void TongSoNguyenTo()
{
var tongchiahet = 0;
for (var so=2;so<20;so++)
{
for (var chia=1;chia<=so;chia++)
{
if (so % chia == 0)
{
tongchiahet++;
if (tongchiahet == 2)
{
Console.WriteLine(so);
}
}
}
}
Console.ReadKey();
}
but instead of list of number, it can write one number. what can i do next
You have issues in your second loop, I don't get the why you used the variable tongchiahet, The main thing that you have to use is a break statement, which helps you to stop iteration of second loop if so % chia == 0 in between iterations: Here is a working Example for you, And try the following code:
int limit = 20;
for (var so = 1; so < limit; so++)
{
bool isPrime = false;
for (var chia = 2; chia < so; chia++)
{
if (so % chia == 0)
{
isPrime = true;
break;
}
}
if (!isPrime)
Console.WriteLine(so);
}

Is there any way I can make this C# code faster? [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 6 years ago.
Improve this question
I am reading in a large file X12 and parsing the information within. I have two bottleneck functions that I can't seem to work around. read_line() and get_element() Is there any way I could make these two functions faster? The main bottleneck in the get_element function seems to be the Substring method.
public String get_element(int element_number) {
int count = 0;
int start_index = 0;
int end_index = 0;
int current_index = 0;
while (count < element_number && current_index != -1) {
current_index = line_text.IndexOf(x12_reader.element_delimiter, start_index);
start_index = current_index + 1;
count++;
}
if (current_index != -1) {
end_index = line_text.IndexOf(x12_reader.element_delimiter, start_index);
if (end_index == -1) end_index = line_text.Length;
return line_text.Substring(start_index, end_index - start_index);
} else {
return "";
}
}
private String read_line() {
string_builder.Clear();
int n;
while ((n = stream_reader.Read()) != -1) {
if (n == line_terminator) return string_builder.ToString();
string_builder.Append((char)n);
}
return string_builder.ToString();
}
I am reading x12 data. Here is an example of what it looks like. http://examples.x12.org/005010X221/dollars-and-data-sent-together/
Since your profiler tells you get_element is a bottleneck, and the method itself is coded very efficiently, you need to minimize the number of times this method is called.
Calling get_element repeatedly in a loop forces it to performs the same parsing job repeatedly:
for (int i = 0 ; i != n ; i++) {
var element = get_element(i);
... // Do something with the element
}
You should be able to fix this problem by rewriting get_element as GetElements returning all elements as a collection, and then taking individual elements from the same collection in a loop:
var allElements = GetElements();
for (int i = 0 ; i != n ; i++) {
var element = allElements[i];
... // Do something with the element
}
in most cases I only need one or two elements
In this case you could make a method that retrieves all required indexes at once - for example, by passing BitArray of required indexes.
Ok, second try. Discarding String.Split due to performance reasons, something like this should work much faster than your implementation:
//DISCLAIMER; typed in my cell phone, not tested. Sure it has bugs but you should get the idea.
public string get_element(int index)
{
var buffer = new StringBuilder();
var counter = -1;
using (var enumerator = text_line.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (enumerator.Current == x12_reader.element_delimiter)
{
counter++;
}
else if (counter == index)
{
buffer.Append(enumerator.Current);
}
else if (counter > index)
break;
}
}
return buffer.ToString();
}
I'm not sure what you are doing exactly, but if I'm understanding your code correctly, wouldn't get element be simpler as follows?
public string get_Element(int index)
{
var elements = line_text.Split(new[] { x12_reader.element_delimiter });
if (index > elements.Length)
return "";
return elements[index];
}

How to input in C# [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 9 years ago.
Improve this question
How to input in C#? and using loop on that input.
Here is my code so far i trying
static void Main(string[] args)
{
int[] ar = new int[10002];
int n = Convert.ToInt32( Console.ReadLine() );
for( int i = 0;i < n; i++ )
{
ar[i] = Convert.ToInt32( Console.ReadLine() );
}
for ( int i = 0; i < n; i++ )
{
Console.WriteLine(ar[i]);
}
Console.ReadKey();
}
Here is a simple example of two ways of handling the invalid input in your case. One thing you can do, is just fail giving the user an information that the input was not correct. Second possibility is to treat invalid input as a null value.
This is just a simple example - usually you shouldn't fail silently (here: return a null and not complain), and you shouldn't use null values as an indicator for a special function return value. Also a good example would be not to finish the program but use a loop to ask the user repeatedly until they learn how a number looks like ;)
These all issues are left unsolved as a practice for the reader ;)
static int? ReadInteger()
{
int result;
if (!int.TryParse(Console.ReadLine(), out result))
{
return null;
}
return result;
}
static void Main(string[] args)
{
int?[] ar = new int?[10002];
int? n = ReadInteger();
if (!n.HasValue)
{
Console.WriteLine("Please input a correct integer");
return;
}
for( int i = 0;i < n.Value; i++ )
{
ar[i] = ReadInteger();
}
for ( int i = 0; i < n.Value; i++ )
{
Console.WriteLine(ar[i].HasValue
? ar[i].Value.ToString() : "Incorrect input");
}
Console.ReadKey();
}
I tried to build this as close as possible to your implementation. The other answer from BartoszKP should be used in a complete scenario.
static void Main(string[] args)
{
int[] ar = new int[10002];
int n;
if (int.TryParse(Console.ReadLine(), out n))
{
int nr;
for (int i = 0; i < n; i++)
{
if (int.TryParse(Console.ReadLine(), out nr))
{
ar[i] = nr;
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(ar[i]);
}
}
Console.ReadKey();
}

Categories