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.
Related
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
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I have a sentence, and I want to check for duplication letters in order to add a 'x' as a separator between them, however I debugged and kept getting an exception in here:
for (int i = 0; i < res.Length; i++)
{
t += res[i];
if (res[i] == res[i + 1]) //Index out of range exception here
{
t += 'x';
}
}
what goes wrong in here?
The cause of misbehavior is in the if:
if (res[i] == res[i + 1])
when i == res.Length - 1 (for loop last iteration) you have
if (res[res.Length - 1] == res[res.Length])
and res[res.Length] throws OutOfRangeException since valid range is [0..res.Length - 1] (please, note - 1).
Your code corrected:
for (int i = 0; i < res.Length; i++)
{
Nplaintext += res[i];
// we don't want to check (and insert 'x') for the last symbol
if (i < res.Length - 1 && res[i] == res[i + 1])
{
Nplaintext += 'x';
}
}
Often we work with string with a help of regular expressions (let .Net loop over the string for you):
using System.Text.RegularExpressions;
...
string source = "ABBBACCADBCAADA";
// Any symbol followed by itself should be replaced with the symbol and 'x'
string result = Regex.Replace(source, #"(.)(?=\1)", "$1x");
Console.Write(result);
Outcome:
ABxBxBACxCADBCAxADA
i+1 us causing this.
in the last iteration, i+1 refers to a location which is not inside that array.
Better change the condition in for loop as below:
for (int i = 0; i < res.Length - 1; i++)
{
t += res[i];
if (res[i] == res[i + 1]) //Index out of range exception here
{
t += 'x';
}
}
t += res[res.Length -1 ];
Hope this helps.
Sure you get this exception. In the case i=res.Length -1 (what is exactly the last position) you ask for res[Length] with the i +1 but because of starting with 0 the element you are asking for does not exist.
try something like
if(i+i < res.Length)
before you ask for that element
or even better start counting with i=1 and use
if (res[i] == res[i - 1])
{
Nplaintext += 'q';
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm a newbie to C# Programming and we're still starting on the loops. For our exercise today, we were tasked to create program using (while loop).
the question is :
Read 5 marks from the user, print the sum and "Passed" if the marks greater or equal to 50 or if among the marks there is only one mark less than 50.
if the user enters 2 marks less than 50 then the program should print STOP and end the program.
this is my try
unfortunately not complete and I can't do it
May you help me, please ?
int sum=0 , counter = 0, number=0 ;
while (counter < 5 || number < 50)
{
number = Convert.ToInt16(Console.ReadLine());
sum = sum + number;
counter++;
}
Console.WriteLine(sum + "\nPassed");
In the while loop you need && (and) instead of || (or).
After reading a number you can check if it's less than 50 or not and you can also count these.
So after the loop you need to check the lessCounter to decide to print Passed or STOP.
int sum = 0, counter = 0, number = 0, lessCounter = 0;
while (counter < 5 && lessCounter <= 1)
{
number = Convert.ToInt16(Console.ReadLine());
sum += number;
if (number < 50)
lessCounter++;
counter++;
}
if (lessCounter <= 1)
Console.WriteLine(sum + "\nPassed");
else
Console.WriteLine(sum + "\nSTOP");
Thank you all for all your effort and a time, special thanks to Mr.Szkup.
I was able to do it this way:
int number = 0, sum = 0, count = 0;
while (number < 5)
{
Console.Write("Input Number {0} : " , (number + 1));
int mark = Convert.ToInt16(Console.ReadLine());
if (mark < 50)
{
count++;
}
if (count == 2)
{
Console.WriteLine("\nStop\n");
break;
}
sum += mark;
number++;
}
if (count <= 1)
{
Console.WriteLine("\nsum = {0}\nPassed\n",sum);
}
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("*");
}
}
}
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