C# How to I escape 2 lines of loops - c#

This is my code:
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
break; //break out of while loop also
}
}
}
How should i do this please, sorry if my english is good,i still learning.

Change your while loop to a variable, then set that variable to false (your isDead variable for instance)
while(!isDead){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
break; //break out of while loop also
}
}
}
That way, your break will get you out of the for loop, then having the isDead set to true will stop the while loop executing.

create a function inline, and call it. use return from within the lambda.
var mt = () => {
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
return
}
}
}
}
mt();

So as I understand you wanted to break 2 Loops on one condition. You can do the following
bool DirtyBool = true;
while(DirtyBool)
{
for(int x = 0; x < 10; x++)
{
StringArray[x] = new string();
if(isDead)
{
DirtyBool = false;
break; //break out of while loop also
}
}
}

You could create a bool for example:
bool leaveLoop;
And if isDead is true then set leaveLoop to true, in the while loop then check if the leaveLoop is true to break from it.

Try below:
bool bKeepRunning = true;
while(bKeepRunning){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
bKeepRunning = false;
break;
}
}
}

My favorite approach to this sort of situation is to move the code into a separate routine and simply return from it when I need to break. Two loops is as much complexity as I like to include in a single routine anyway.

You can use goto:
while(true){
for(int x = 0; x < 10; x++){
StringArray[x] = new string();
if(isDead){
goto EndOfWhile; //break out of while loop also
}
}
}
EndOfWhile: (continue your code here)

Related

How do I return a value from within a loop within a function?

If I have a loop in a function, how do I return a value from within the loop?
In this example I'm using a loop to figure out if a number is prime. If I figure out the answer then I don't want the loop to continue. I just want to return it.
private int IsPrime (int startNumb , int endNumb)
{
bool bilPrima = true;
for (int i = startNumb; i<= endNumb; i++)
{
for (int j = 2; j <= i; j++)
{
if (i%j==0)
{
bilPrima = false;
break;
}
}
if (bilPrima)
{
bilPrima = true;
return i;
}
else
{
return 0;
}
}
}
If a function contains a loop, but the return value of the function can be determined before the loop has completed, you can just return the return value, and execution of the function will end.
So your function could look like this:
private bool IsPrime(int startNumb, int endNumb)
{
for (int i = startNumb; i <= endNumb; i++)
{
for (int j = 2; j <= i; j++)
{
if (i % j == 0)
{
return false;
}
}
}
return true;
}
One of the comments suggested that you might want to return a list of prime numbers. If that's the case then the answer would be completely different.
You could return an IEnumerable<int>. Within your function, create a List<int>. As you loop through values, every time you find a prime number add it to the list. Then at the end of the function, return the list.
You can do the same thing with yield return - I'm just trying not to overload you.

C#: Cannot reassign variable within For loop

I am writing a program to to calculate a specific value in Fibonacci sequence. The recursive method works perfectly, but when I try to use for loop, it doesn't work so well:
class Program
{
static int loopF(int n)
{
int result=0;
if (n == 1)
{
result = n;
}
else if (n == 2)
{
result = n;
}
else if (n>2)
{
int S1 = 1; int S2 = 2;
for (int i = 3; i>n; i++) {
result = S1 + S2;
S1 = S2;
S2 = result;
}
}
else{
Console.WriteLine("Input Error");
}
return (result);
}
static void Main()
{
Console.WriteLine(loopF(10)); //it gives me 0; wrong
Console.WriteLine(loopF(1)); //it gives me 1; correct.
}
}
Does anybody know where I go wrong? Thanks in advance.
Your loop is not executing
for (int i = 3; i>n; i++)
Variable i starts at 3 - in your test case n = 10.
(10 < 3) = false so the loop does not execute.
try using less than instead
for (int i = 3; i < n; i++)
Your loop's exit condition is wrong. It should be
for (int i = 3; i < n ; i++) { ...

Increment variable after third time something else happened

Excuse me for the silly question, but i can't manage to solve it.
How can i make something to happen every third time ?
Times(left number):
shipmentId=0
shipmentId=0
shipmentId=1
shipmentId=1
shipmentId=2
shipmentId=2 ....
int occurrence = 0;
int counter = 0;
foreach (var el in elmOrderData)
{
if (el.Name == "shipmentIndex")
{// we are entering here for every element that his name is "shipmentIndex"
el.SetValue(shipmentId);
secondTime++;
}
if ((secondTime % 2) == 0)
{// every third time we see "shipmentIndex"
secondTime = 1;
shipmentId++;
}
}
You could use a bool as in the following example. This will display messageboxes 1,3,5,7 and 9:
bool test = false;
for (int i = 0; i < 10; i++)
{
if (test)
MessageBox.Show(i.ToString());
test = !test;
}
Trying to piece together your notes - whether 'it' happens every time or not. How about this?
int occurrence = 0;
int counter = 0;
foreach(var a in list)
{
if(some_condition)
{
// do something..
occurrence++
if(occurrence % 2 == 0)
{
counter++
}
}
}
Why not just increment everytime and just divide by 2?
for(var i = 0; i<20; i++)
{
var j = i / 2; // or bit shift
//do work on j instead of i
}

Many else and if statements?

I am reading a csv file which has column names in first line and values in line >1. I need to get the position of the column name. The only way I can think of is to do either switch or ifs. I read it somewhere that in my case , it is faster (better) to do the ifs. However the file has many columns (~120). Just wondering if there is an alternative(s).
private static void Get_Position(string line, performance p)
{
string[] line_split = line.Split(',');
for (int i = 0; i < line_split.Length; i++)
{
if (line_split[i].Contains(#"(0)\% Processor Time"))
{
p.percore[0] = i;
}
else if (line_split[i].Contains(#"(1)\% Processor Time"))
{
p.percore[1] = i;
}
else if (line_split[i].Contains("Private Bytes"))
{}
else if (line_split[i].contains("DPC")
{
}
//on and on and on with else ifs
What is preventing you from using a loop?
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(#"(" + j + ")\% Processor Time"))
{
p.percore[j] = i;
}
}
...
To maintain the same functionality as if else if then you could use a break inside the conditional.
Edit: The edit now made it clear that there is no clear pattern to the string in contains. Still, if you are writing out 120 if/else if statements you should store what you will be looking for in some type of collection. For example, a List would work. Then access the index j of the collection in your loop:
...
var listOfSearchItems = new List<string>() { "Private Bytes", "DPC" };
for (int i = 0; i < line_split.Length; i++)
{
for(var j = 0; j < 120; j++)
{
if(line_split[i].Contains(listOfSearchItems[j])
{
p.percore[j] = i;
}
}
...

How to reset or restart nested loops

loop one
{
looptwo
{
if(condition=true)
{
reset values//restart both loops
}
}
}
and possibilities for reset values is 3
basically i want to compair two matrices
a= 1 2 3 4
1 2 3 4
b= 3 4 5 6
4 6 7 8
and when row 1 of a[] is matched with row 1 of b[].....i will add these rows and a[]
become = 2 4 6 8
for(i=0;i<rows;i++)
for(j=0;j<columns;j++)
{
a[i]=a[i]+b[i,j]
}
and again find my maches from restart with new a[] Matrix
and i have to insure that all rows of b[] matrix are checked with a[] which are 3 in this case
You have to use goto to break out of multiple loop levels in C#. For example:
RESTART:
while (a) {
while (b) {
if (that_other_thing)
goto RESTART;
}
}
Well, you don't have to use goto but the alternative might be using a bunch of flag variables to indicate that a restart is required. And that code will probably be pretty hard to follow.
The best choice here is to move the loops into their own method, and return from inside the inner loop. Example:
public void MyMehod(){
loop one{
looptwo{
if(condition=true){
return;
}
}
}
}
If this is not possible for some reason, you can use a bool value that you set in the inner loop to bail out of all of them, but this is a bit more messy:
bool endloop = false;
while(!endloop){
while(!endloop){
if(condition){
endloop = true;
}
}
}
For a while loop it looks ok, but even more messy for a for loop or a foreach loop.
Start:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if(j == 5)
goto Start;
}
}
Although structuring your code in a way to not use a goto is a much better approach...
If you can guarantee that you will have a condition that will tell you that you don't need to restart, you could wrap the whole thing in one more loop.
bool keepLooping = true;
while (keepLooping)
{
keepLooping = false;
for (int x = 0; x < maxx; x++)
{
for (int y = 0; y < maxy; y++)
{
if (DoSomething(x, y))
{
keepLooping = true;
break;
}
}
if (keepLooping)
{
break;
}
}
}
If you are checking a list for duplicates and modifying them do make all entries unique, you might do something like this (assuming string values):
List<string> a = GetNamesFromeSomewhere();
bool duplicateFound = true;
while (duplicateFound )
{
duplicateFound = false;
for (int x = 0; x < a.Length; x++)
{
for (int y = x + 1; y < a.Length; y++)
{
if (a[x].Equals(a[y]))
{
//Change a[y], but now we have to recheck for duplicates...
a[y] += "_";
duplicateFound = true;
break;
}
}
if (duplicateFound)
{
break;
}
}
}
if you use numeric loop variables like i and j you can just reset the values
e.g.
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (var[i][j] == 'x') {
i=0; j=0; break;
}
}
}
you can also use the method approach as suggested earlier
void someFunction(params) {
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (var[i][j] == 'x') {
someFunction(params)
return;
}
}
}
}

Categories

Resources