Exiting loop without break/return/if - c#

If you have a for loop:
for(i=0;i<10;i++){}
Now, when i==5, how can I exit the for loop completely without using break, return, or if?

The best I could come up with was this:
for (int i = 0; i < 10; i++)
{
i = (i == 5) ? 10 : i;
Trace.WriteLine("i = " + i.ToString());
}
...which will cause the loop to run six times (i=0..5) and display this..
i = 0
i = 1
i = 2
i = 3
i = 4
i = 10
The alternative way to "exit the loop" (in a particularly nasty fashion) would be to do this...
for (int i = 0; i < 10; i++)
{
int a = 3 / ((i == 5) ? 0 : 1);
Trace.WriteLine("i = " + i.ToString());
}
..which crashes out, errr, successfully exits the loop without using the break, return or if commands.
i = 0
i = 1
i = 2
i = 3
i = 4
A first chance exception of type 'System.DivideByZeroException' occurred in MikesProgram.dll
language is C# .it was an interview question actually..curious
Do I get the job ?
I would need to check your health & dental plans, and I have to leave early on Thursdays to collect my daughters from school.
;-)

for (int n = 0; n < 10; n++)
{
n += (n / 5) * 5;
}

well here's another way if you want to break the processing exactly when i = 5 without using break, return, or if
for (int lowsetLimit = 0, highestLimit = 10, i = lowsetLimit; i < highestLimit; i++)
{
//normal code which process before i gets eqaul to 5 goes here...
i = (i < 5) ? i : highestLimit; //and here is the pivot point.
}

for(i=0;i<10;i++){
(i==5) ? goto Outer : //do something;
}
Outer:
//do something

The question says that loop should end when i=5, It says nothing about start, So this should be valid (ternary operator solution is better, but if we are not allowed to use any conditional operator)
for (int i = 0; i < 10; i++)
{
i=i-4;
Console.WriteLine("i = " + i.ToString());
i=i+4;
}
this Starts at -4 and ends at 5.

The real answer of course would be the following:
for (i=0; i!=5; i++)
{
// do something
}
But let's make it a bit more generic: stop if (expression) becomes true.
The second argument of the for loop is a boolean expression which determines whether to continue the loop with the next element or not.
So if you want to stop looping because of any condition:
for (i=0; !(expression) && i<10; i++)
{
// do something
}

This works using while and goto:
for (int i = 0; i < 10; i++)
{
while (i < 5)
{
Console.Write(i + " ");
goto OutsideWhile;
}
OutsideWhile:
continue;
}
// 0 1 2 3 4

Related

How can I have x many symbols on the first line then adding 1 more each line until it hits the end value with a for loop?

So I want to recreate this process with a for loop. What's the simplest way of doing this. I can do 1 to 10 but let's say you have 3 as your start value I can't get the first line to start with 3 symbols.
Thanks in advance.
Since you haven't shared any code, I'll give you an idea as to how you can print the values. I've used 2 for loops to print the value. Although there maybe better and shorter algorithms to do the same
Just edit my code below to suit your needs.
public static void Main()
{
var start = 3; //StartTextBox.Text
var end = 10; //EndTextBox.Text
var symbol = "#"; //SymbolTextBox.Text
for (var i = start; i < end; i++)
{
var toPrint = string.Empty;
for (var j = 0; j < i; j++) toPrint += symbol;
Console.WriteLine(toPrint); //LabelX.Text = toPrint;
}
Console.ReadLine();
}
You can see in the above code that if you change the value of start to any number, the value gets printed properly.
Another option assuming some of your object names...
for (int i = int.Parse(txtStart.Text); i <= int.Parse(txtEnd.Text); i++)
{
lblOutput.Text += new String(txtSymbol.Text.ToCharArray()[0], i) + Environment.NewLine;
}

How to reverse the print out of numbers

I'm currently trying to learn C# for my university degree and I can't work out how to get my code to print out only the even numbers from 0-100 starting at the largest number i.e 100 down too 0. I have the code printing the output from smallest to largest but cannot get it to go the other way around.
Can anyone give me a hand?
This is my code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 1; i < 100; i++)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
You need to replace your code with this code:
Console.WriteLine("Print first 100 even No in reverse");
for (int i = 100; i >= 0 ; i--)
{
if (i % 2 == 0)
{
Console.Write(i + " ");
}
}
you just need to start your loop from 100 and decrease from there:
for (int i = 100; i >= 0; i--)
use ">" instead of ">=" operator, if you don't want the zero included

how continue, the jump statement affects for loop 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 5 years ago.
Improve this question
i am reading C-Sharp 7.0 in a Nutshell - Joseph Albahari,
in jump statements section, there is a code like
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0) // If i is even,
continue; // continue with next iteration
Console.Write (i + " ");
}
Output is : 1 3 5 7 9
but when i comment the continue jump statement like below
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0) // If i is even,
//continue; // continue with next iteration
Console.Write (i + " ");
}
Output is : 0 2 4 6 8
can someone explain how continue statement affects flow of loop ?
Without the curly brackets, C# will compile the next statement to be executed when the condition of the if is true. A comment is not a statement. This is one of the main reasons it's best to always include curly brackets, even with a single statement.
continue tells the program to jump to the start of the loop and retest the condition. In this case the Console.Write calls will be skipped.
There is also break which ends the loop completely and does not retest the condition.
Your fundamental confusion I think has to do with the fact that commenting out a statement removes the statement entirely. It does not make a "do nothing" statement that is then the body of the if.
However, I think there is also a confusion expressed about what continue does. A good way to understand this is to reduce it to something simpler.
Suppose you have
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0)
continue;
Console.Write (i + " ");
}
Let's reduce this to a simpler program, in the sense that for is complicated and while is less complicated. Your program fragment is the same as:
{
int i = 0;
while (i < 10)
{
if ((i % 2) == 0)
goto DoTheLoopIncrement;
Console.Write (i + " ");
DoTheLoopIncrement:
++i;
}
}
Which is the same as:
{
int i = 0;
DoTheLoopTest:
if (i < 10)
goto DoTheLoopBody;
else
goto DoneTheLoop;
DoTheLoopBody:
{
if ((i % 2) == 0)
goto DoTheLoopIncrement;
Console.Write (i + " ");
DoTheLoopIncrement:
++i;
goto DoTheLoopTest;
}
}
DoneTheLoop:
...
Notice how much longer and harder to read the "goto" version is. That's why we use while and for. But you must understand that this is precisely what while and for and continue are doing in order to make sense of their control flows. They are just a pleasant way of writing a goto.
Now: do you understand what break means? Break is just a pleasant way to write goto DoneTheLoop.
Poor formatting:
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0) // If i is even,
continue; // continue with next iteration
Console.Write (i + " ");
}
Better formatting:
// Output is : 1 3 5 7 9
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0) // If i is even,
continue; // continue with next iteration
Console.Write (i + " ");
}
Without "continue":
// Output is : 0 2 4 6 8
for (int i = 0; i < 10; i++)
{
if ((i % 2) == 0) // If i is even,
// continue; // continue with next iteration
Console.Write (i + " ");
}
Best formatting:
// Output is : 1 3 5 7 9
for (int i = 0; i < 10; i++)
{
// If i is even,
if ((i % 2) == 0)
{
// continue with next iteration
continue;
}
Console.Write (i + " ");
}
Continue will ignore all the statements that follow inside the loop and continue with the next iteration.

Square of Stars [closed]

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 6 years ago.
Improve this question
namespace SquareStars
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
for (int i = 0; i <n-1; i++)
{
Console.Write("*");
}
for (int i = 0; i < n-1; i++)
{
Console.WriteLine("*");
}
for (int i = 0; i < n; i++)
{
Console.Write("*");
}
}
}
}
My exercises is to do Square of Stars like this:
depends of "n".I try to use for loops,but I can do right side of square.
I do this:
***
*
***
but I want this:
*** ****
* * * *
*** or * *
****
Can sameone help me to this code????
The following should do:
public static string CreateASCIISquare(int squareSideLength, char c = '*')
{
if (squareSideLength < 1)
return "";
if (squareSideLength == 1)
return c.ToString();
var horizontalOuterRow = new String(c, squareSideLength);
var horizontalInnerRow = $"{c}{new string(' ', squareSideLength - 2)}{c}";
var squareBuilder = new StringBuilder();
squareBuilder.AppendLine(horizontalOuterRow);
for (int i = 0; i < squareSideLength - 2; i++)
{
squareBuilder.AppendLine(horizontalInnerRow);
}
squareBuilder.Append(horizontalOuterRow);
return squareBuilder.ToString();
}
Ok, so lets explain the code a little bit:
Always validate the data going into your method. In your case the user can specify the length of the square's side. Are there any invalid values? Well clearly yes, -2 doesn't seem to be a valid choice.
You have many options here. You can tell the user the value is not valid, you can simply ignore it, do nothing and let your application crash and die miserably, or you can return an empty square. All are valid choices, but consciously choose one and design according to your decision. In my case I chose to return an empty square:
if (squareSideLength < 0)
return "";
Are there any trivial cases I can manage easily without for loops and Console.Writes etc.? Yes, lengths 0 and 1 seem pretty straightforward. It stands to reason that if I've returned the empty square for negative values, I do the same for 0 sized squares. So I change the previous code to:
if (squareSideLength < 1)
return "";
Good, now what about 1? Well that's pretty easy too isn't it?
if (squareSideLength == 1)
return c.ToString();
Moral of the story: take care of invalid data or trivial cases first. Many times trivial cases can also be corner cases that can complicate your general solution, get them out of the way fast!
Ok, now lets think about what a square looks like:
**
**
***
* *
***
****
* *
* *
****
Well the pattern seems pretty obvious. A square is made up of two rows containing the specified number of stars, and 0 or more rows containing only 2 stars and squareSideLength - 2 spaces in between. Well, its only two types of rows, lets build them up front:
var horizontalOuterRow = new String(c, squareSideLength);
var horizontalInnerRow = $"{c}{new string(' ', squareSideLength - 2)}{c}";
Great! We got our building blocks, now lets build our square:
So how does that go? Well we simply start by adding a horizontalOuterRow then we add the squareSideLength - 2 horizontalInnerRows and we finish up adding one more horizontalOuterRow.
And voilá, we got ourselves our nice little ASCII square:
squareBuilder.AppendLine(horizontalOuterRow);
for (int i = 0; i < squareSideLength - 2; i++)
{
squareBuilder.AppendLine(horizontalInnerRow);
}
squareBuilder.Append(horizontalOuterRow);
The fact that I've used a StringBuilder is not really germane to the question, but get into the habit of using this tool when constructing dynamically built strings you don't know the length of beforehand. Concatenating strings can give you pretty bad performance so it's best to avoid it if possible.
Now we proudly return our beautiful ASCII square back to our extatic user and bask under the general round of applause:
return squareBuilder.ToString();
Hope this little answer helps you.
Remember, to code well, break everything up into very small tasks, and take care of them one at a time. Think how you'd do it by hand and write it that way. Once you have it working there'll be time to see if you need to optimize, refactor, etc. your code. But the key is getting it to work with code as clear as possible.
You can use the string(char, int) constructor to create strings of repeating characters. This lets you simplify the code to use a single for loop:
var n = int.Parse(Console.ReadLine());
Console.WriteLine(new string('*', n));
for (int i = 0; i < n - 2; i++)
{
Console.WriteLine("*" + new string(' ', n - 2) + "*");
}
Console.WriteLine(new string('*', n));
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
for (int row = 1; row <= n; row++)
{
for (int col = 1; col <= n; col++)
{
if (row == 1 || row == n)
{
Console.Write("*");
}
else
{
if (col == 1 || col == n)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
}
Console.WriteLine();
}
Console.ReadKey();
}
}
You can change Console.WriteLine in 2nd loop like this :
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
for (int i = 0; i < n - 1; i++)
{
Console.Write("*");
}
for (int i = 0; i < n - 1; i++)
{
Console.WriteLine(i == 0 ? "*" : "*" + string.Empty.PadLeft(n - 2) + "*");
}
for (int i = 0; i < n; i++)
{
Console.Write("*");
}
}
}

C# & VS error: "make sure that the maximum index on a list is less than the list size"

I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with:
public static double LaskeMiidi(double[] luvut)
{
double ka = Keskiarvo(luvut);
double miidi = luvut[0];
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to!
{
miidi = luvut[i];
}
else
{
miidi = luvut[i + 1];
}
}
return miidi;
}
So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.
Yes, this is the problem:
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka)
When i is luvut.Length - 1, then i + 1 will be luvut.Length - and therefore an invalid index. (For an array of length x, the valid indexes are 0 to x - 1 inclusive.) You probably want to end one iteration earlier:
for (int i = 0; i < luvut.Length - 1; i++)
That way i + 1 will still be a valid index in the array - both in the if condition and in the body of the else clause.
End your loop earlier:
for (int i = 0; i < luvut.Length - 1; i++)
This stops the loop ever getting to the point where an index would be invalid.
When i = luvut.Length -1, luvut[i + 1] will give an error as it is beyond the array bounds.
You need either:
for (int i = 0; i < luvut.Length - 1; i++)
Or else handle the luvut[i + 1] issue in another way in another If block.
Notice that when you define an array, range of items are between 0 and array.length-1. so you should write:
for (int i = 0; i < luvut.Length-1; i++)

Categories

Resources