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
I am a beginner C# learner. I am trying to learn through an app called SoloLearn.
In the app, it wants me to replace 3 and its multiples in a series of numbers with "*".
For example; the input is n number, let's say 7, the output should go "12 * 45 * 7" (without spaces)
I tried this, it worked but these two "ifs" at the end make my eyes bleed.
using System;
using System.Collections.Generic;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
//your code goes here
for (int x = 1; x <= number; x++)
{
if (x%3==0)
Console.Write("*");
if (x%3==0)
continue;
{
Console.Write(x);
}
}
}
}
}
I played around it a little but can't seem to find any way around it.
How would you shorten these only with the content in this code given?
You don't need a continue statement there. Instead of two ifs you could use an if and an else, e.g.:
for (int x = 1; x <= number; x++)
{
if (x % 3 == 0)
{
Console.Write("*");
}
else
{
Console.Write(x);
}
}
For fun:
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
var seq = Enumerable.Range(1, number).Select(x=>x%3==0?"*":x.ToString());
Console.WriteLine(string.Join("", seq));
}
And I could, of course, shorten it further to a single line, but that just seems excessive. There's probably also a way to get an implicit ToString() conversion.
The slightly shorter version of the for loop is this:
for (int x = 1; x <= number; x++)
{
Console.Write(x % 3 == 0 ? "*" : $"{x}");
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
public static void Main()
{
int i, j;
Console.Write(" ");
for (i = 1; i < 10; i++)
Console.Write(String.Format("{0,3:d}", i));
Console.WriteLine();
for (i = 0; i < 32; i++)
Console.Write("=");
Console.WriteLine();
for (i = 1; i < 10; i++)
{
Console.Write(i + " | ");
for (j = 1; j < 10; j++)
Console.Write(String.Format("{0,3:d}", i * j));
Console.WriteLine();
}
Console.ReadKey();
}
Some person did show me this piece of code and told that
Any programmer, systems engineer, or systems mathematician who has seriously studied C# should know the answer.
I don't see anything too wrong with it.
It has table limits hardcoded (10), but the table itself is for 9 numbers only, so this is not a crime.
Doing i + " | " is not very nice for performance and memory usage, but this is such trivia.
The person does not respond to me what's was wrong with this code, I can't sleep now thinking about it!
This question might be better asked here: Code review
Correctness: it behaves correctly
Readability: simple program, not too bad
Efficiency: not too bad either
Flexibility: poor - I suggest implementing a more generalized method which takes a table width/height parameter
Other: String-handling is a bit archaic (can use string interpolation)
Beyond these few comments I can see a couple of reasons one might argue religiously, i.e. not about right and wrong but about "best practice" (dogma) - like use of braces
I tried to minimize and optimize the code and add support for determining the range (min/max) of the table to be printed so that it calculates the necessary space for longer numbers.
Many programmers are allergic to the missing parentheses for single line subblocks (conditions or loops), but I'm more comfortable without them, the code is not as long and so much more readable for me. But it's more about habit. Maybe they have it as a mandatory convention in that company, but then I would have other comments on code optimization than this irrelevance.
In Python, they also just indent instead of bracket and nobody there minds.
using System;
using System.Linq;
MultipleTable(1, 9);
void MultipleTable(int min, int max)
{
int minDigits = max.ToString().Length,
maxDigits = (max*max).ToString().Length;
Console.Write(" | ".PadLeft(minDigits+3));
Console.WriteLine(String.Join(" ",
Enumerable.Range(min, max-min+1)
.Select(x => x.ToString().PadLeft(maxDigits))));
Console.WriteLine("".PadRight((max-min+1)*(maxDigits+1)+minDigits+3, '='));
for (int i = min; i <= max; i++)
{
Console.Write(i.ToString().PadLeft(minDigits) + " |");
for (int j = min; j <= max; j++)
Console.Write((i*j).ToString().PadLeft(maxDigits+1));
Console.WriteLine();
}
}
You can try it in SharpLab.
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 1 year ago.
Improve this question
var input = Convert.ToInt32(Console.ReadLine());
for (var i = 1; i <= input; i++)
{
for (var tr = 1; tr <= input; tr++)
{
for (var ch = 1; ch <= input; ch++)
{
if (ch <= i) Console.Write("+");
else Console.Write(" ");
}
}
Console.WriteLine();
}
The program outputs triangles. The code uses three loops. How to make it so that there are only two loops and the program works the same as before?
Notice in the pattern of triangles that on the first line you print 1 + then print n-1 blanks repeatedly. On the second line you print two + then print n-2 blanks repeatedly.
To decide if you need to print a plus or a blank you can use modulo arithmetics. if c % n < lineno print + else print a blank.
You print n * n characters in each line.
That's not the complete code but a good boost to implement the solution.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 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 tried to make a FizzBuzz code in C# but the error code it gives me is that I'm missing a " , " somewhere but I can't find where to place it
Also I know there are other underlying programs in the code I just need this fixed so I can compile and fix them
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
float i = 0;
if (i != 101)
{
i = i + 1;
float i3 = i / 3;
float i5 = i / 5;
float i15 = i / 15;
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
else if ((i3 % 1) > 0)
{
string Hold = ("Buzz");
Print = Hold;
}
else if ((i15 % 1) > 0)
{
string Hold = ("FizzBuzz");
Print = Hold;
}
Console.WriteLine(Print)
; Console.WriteLine("Done");
Console.ReadLine();
}
}
}
}
Fizz-Buzz was originally a game designed to teach children division, it worked like this:
The player designated to go first says the number "1", and each player counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz.
So your program has a number of errors, first one is that you use an if where you should be looping. Your first if statement:
if (i != 101)
{ ... }
Really doesn't do anything. You set i=0 in the previous statement, so i will never equal 101. What you need to do instead is a while loop:
float i = 0.0f;
while (i < 101.0f)
{
//Run the program
}
The next problem you have is that it is OK to use i for an iterator, or even x or y if iterating dimensions, but that is really where the single letter variables should stop. Use meaningful names, it makes things much easier:
So, again we need to check if i is divisible by 3, 5, or both. We can do that with simple boolean variables, no need to make things more complicated.
bool divisibleBy3 = i % 3.0f == 0.0f;
bool divisibleBy5 = i % 5.0f == 0.0f;
The next thing you have wrong is that you have ; in strange places, namely you seem to mix them in on separate lines. Try not to do this. There are very few reasons that a ; should not be on the end of every code line, and there should really only be one per line. So this:
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
Is an error because it treats it all as one line until it hits the ;, so your code really becomes:
string Print = Convert.ToString(i) else;
if (...)
And it should be obvious what the problem with that is.
The last problem I'll touch on really isn't a code issue, but a form one. You have a lot of "holding" variables that don't do anything but temporarily put things in places then put them somewhere else, like this:
if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
What is the purpose of Hold? You could just write:
Print = "Fizz";
The ( and ) are also unnecessary. So lets take all these lessons and put them into the Fizz-Buzz program:
int i = 0; //No reason to use float here, int is just fine
while (i <= 100)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
i += 1;
}
Console.WriteLine("Done");
Console.ReadKey(true);
Or, it can be written with a for loop:
for (int i = 0; i <= 100; i++)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
}
Console.WriteLine("Done");
Console.ReadKey(true);
So you can see how giving variables meaningful names, paying attention to indenting/formatting, and understanding of the ; can help you make debugging easier. Clean, well formatted code is easy to read and debug, and giving variables meaningful names means you can tell what the purpose is without having to read through the entire use of the variable.
Note: Some programmers will argue that Fizz-Buzz can be condensed down to 1-3 lines of code. While it is possible, I would argue that it doesn't demonstrate good programming practices. There is a big difference between readable code that can be maintained, and just making something short for the sake of it being short.
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 6 years ago.
Improve this question
I am trying to divide BigIntegers.
this is my code so far:
BigInteger x = BigInteger.Parse("2697841949839130393229424953460693359375000000");
BigInteger y = BigInteger.Parse("2");
for (int i = 0; i < 300; i++) {
double result = Math.Exp(BigInteger.Log(x) / BigInteger.Log(y));
x = result;
Console.WriteLine(result);
}
It does the divide. it does it only once. I want to divide the code to minimum it has. it should be 6.
I know that this:
for (int i = 0; i < 300; i++){}
is not the right way to do it. does any one know any other way how to?
I remember from your other question that you are trying to decode Godel numbers.
You shouldn't stick the result in a double. It's too big. You're looking for BigInteger's Divide method. For your application DivRem is better.
Here's some sample code. It computes 6. This should get you going for the first character. You'll also need to build a list of primes beyond '2' to continue on to the rest of the string.
using System;
using System.Numerics;
public class Program
{
public static void Main()
{
BigInteger x = BigInteger.Parse("2697841949839130393229424953460693359375000000");
BigInteger y = BigInteger.Parse("2");
int counter = 0;
BigInteger remainder;
do{
BigInteger result = BigInteger.DivRem(x, y, out remainder);
if(!remainder.IsZero)
break;
x = result;
counter++;
} while (true);
Console.WriteLine(counter);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
I'm trying to do a Prime Number finder but cant see why it's not working.
When i run the debug test nothing show in the console. Could someone check it and tell me what i do wrong?
List<int> primes = new List<int>();
primes.Add(2);
primes.Add(3);
int maxPrime = 11; //The maximum found Primes
int primeCount = primes.Count; //Current Number of Primes
int num = 4; //Current Number
int x = 0; //
int curPrime = primes[x];
while (primeCount < maxPrime)
{
if (x != primeCount)
{
if (num % primes[x] == 0)
{
num++;
x = 0;
}
else
{
x++;
}
}
else
{
primes.Add(num);
primeCount=primes.Count;
x = 0;
}
}
primes.ForEach(i => Console.Write("{0}\t", i));
You have an infinite loop.
Since you never modify primeCount or maxPrime, this will always be true:
while (primeCount < maxPrime)
In order to end that loop, you need to modify one of those two values in such a way that the condition will evaluate to false.
(Note: There appear to also be other bugs/problems in the code aside from this. For example, num = num++; doesn't do what you probably think it does.)