Search Results

Search found 12044 results on 482 pages for 'foreach loop'.

Page 2/482 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Addind the sum of numbers using a loop statement

    - by Deonna
    I need serious help diving the positive numbers and the negative numbers. I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the loop, you are then to display the sum of the negative values and the sum of the positive values. The data is suppose to look like this: -2.3 -1.9 -1.5 -1.1 -0.7 -0.3 0.1 0.5 0.9 1.3 1.7 2.1 2.5 2.9 Sum of negative values: -7.8 Sum of positive values: 12 So far I have this: int main () { int num, num2, num3, num4, num5, sum, count, sum1; int tempVariable = 0; int numCount = 100; int newlineCount = 0, newlineCount1 = 0; float numCount1 = -2.3; while (numCount <= 150) { cout << numCount << " "; numCount += 2; newlineCount ++; if(newlineCount == 6) { cout<< " " << endl; newlineCount = 0; } } **cout << "" << endl; while (numCount1 <=2.9 ) { cout << numCount1 << " "; numCount1 += 0.4; newlineCount1 ++; } while ( newlineCount1 <= 0 && newlineCount >= -2.3 ); cout << "The sum is " << newlineCount1 << endl;** return 0; }

    Read the article

  • Using foreach loop.

    - by Harikrishna
    I break the code of the for loop without using break like I have for loop given below.And when i is 1 or 2 or 3 or any else but if condition is true then loop will be terminated because i will be 5 if the condition is true.And so NO need of break is needed there.Beacause I do not want to use break.I have done like this here.It works. bool myCondition=false; for(int i=0;i<5;i++) { if(myCondition) { i=5; } } But now I want to use foreach loop and in this loop when some condition is true then I want to break the foreach loop code.So what should I do here for breaking the foreach loop code without using break ? Like in the above for loop I have initialize i to 5 when condition is true.In the foreach loop anything like that to do to avoid break.

    Read the article

  • Recommended main loop style

    - by Frootmig-H
    I've just begun attempting an FPS with JMonkeyEngine, but I'm currently stuck as to the best way to implement the main loop - especially with regards to non-instantaneous user actions. By that, I mean things like reloading a weapon. The user starts the action, and it continues for a while with an animation and some sound, and when it completes, game state updates. (I should mention that it's not technically a loop, it's an update method, called as often as possible. Is that different? Me no understand terminology). So, far I've considered : Animation driven Player presses reload Start reload animation If user stars another action, abort animation, start new action. When the animation_complete event is received (JMonkeyEngine provides this), update ammo counters. Event driven Player presses reload Start reload animation Queue up a out-of-thread method to be called at time t + (duration of reload animation) If user starts another action, cancel both animation and queued method. When queued method executes, update ammo. This avoids relying on the animation event (JMonkeyEngine has a particular quirk), but brings in the possibility of thread problems. 'Blocking' (not sure of the correct term) Player presses reload Start reloading animation reloading = true reloadedStartTime = now while (reloading && ((now - reloadingStartTime) < reloadingDuration)) { If user starts another action, break and cancel reloading. } Update ammo counters reloading = false My main concern is that actions can interrupt each other. Reloading can be interrupted by firing, or by dropping or changing weapon, crouching can be interrupted by running, etc. What's the recommended way to handle this? What are the advantages and disadvantages of each method? I'm leaning towards event-driven, even though it requires more care; failing that, blocking.

    Read the article

  • HTML5/JS - Choppy Game Loop

    - by Rikonator
    I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game. I'm trying for a fixed time step loop, rendering only when required. I simply use a requestAnimationFrame to run Game.update which finds the elapsed time since the last update, and calls State.update to update and render the current state. State.prototype.update = function(ms) { this.ticks += ms; var updates = 0; while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) { this.updateState(); this.updateFrameTicks += State.DELTA_TIME; this.updateFrames++; if(this.updateFrameTicks >= 1000) { this.ups = this.updateFrames; this.updateFrames = 0; this.updateFrameTicks -= 1000; } this.ticks -= State.DELTA_TIME; updates++; } if(updates > 0) { this.renderFrameTicks += updates*State.DELTA_TIME; this.renderFrames++; if(this.renderFrameTicks >= 1000) { this.rps = this.renderFrames; this.renderFrames = 0; this.renderFrameTicks -= 1000; } this.renderState(updates*State.DELTA_TIME); } }; But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/1 (Edit). As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended. This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using setTimeout and requestAnimationFrame. (One such example is http://jsbin.com/eyarod/1/edit). Some help and insight would really be appreciated!

    Read the article

  • In .NET which loop runs faster for or foreach

    - by Binoj Antony
    In c#/VB.NET/.NET which loop runs faster for or foreach? Ever since I read that for loop works faster than foreach a long time ago I assumed it stood true for all collections, generic collection all arrays etc. I scoured google and found few articles but most of them are inconclusive (read comments on the articles) and open ended. What would be ideal is to have each scenarios listed and the best solution for the same e.g: (just example of how it should be) for iterating an array of 1000+ strings - for is better than foreach for iterating over IList (non generic) strings - foreach is better than for Few references found on the web for the same: Original grand old article by Emmanuel Schanzer CodeProject FOREACH Vs. FOR Blog - To foreach or not to foreach that is the question asp.net forum - NET 1.1 C# for vs foreach [Edit] Apart from the readability aspect of it I am really interested in facts and figures, there are applications where the last mile of performance optimization squeezed do matter.

    Read the article

  • Mixing Objective-C and C++: Game Loop Parts

    - by Peteyslatts
    I'm trying to write all of my game in C++ except for drawing and game loop timing. Those parts are going to be in Objective-C for iOS. Right now, I have ViewController handling the update cycle, but I want to create a GameModel class that ViewController could update. I want GameModel to be in C++. I know how to integrate these two classes. My problem is how to have these two parts interact with the drawing and image loading. GameModel will keep track of a list of children of type GameObject. These GameObjects update every frame, and then need to pass position and visibility data to whatever class or method will handle drawing. I feel like I'm answering my own question now (talking it out helps) but would it be a good idea to put all of the visible game objects into an array at the end of the update method, return it, and use that to update graphics inside ViewController?

    Read the article

  • javascript game loop and game update design

    - by zuo
    There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like updateEveryNFrames(n, func). I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the counter % n. For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation. Can some give some advice or other solutions?

    Read the article

  • Why is this PHP loop rendering every row twice?

    - by Christopher
    I'm working on a real frankensite here not of my own design. There's a rudimentary CMS and one of the pages shows customer records from a MySQL DB. For some reason, it has no probs picking up the data from the DB - there's no duplicate records - but it renders each row twice. The page PHP is viewable at http://christopher.pastebin.com/DQkjjG3s (attempted to include in this post but it was horribly mangled, think it's important to have it all in context). I'm not the world's best PHP expert but I think I can see an error in a for loop when there is one... But everything looks ok to me. You'll notice that the customer name is clickable; clicking takes you to another page where you can view their full info as held in the DB - and for both rows, the customer ID is identical, and manually checking the DB shows there's no duplicate entries. The code is definitely rendering each row twice, but for what reason I have no idea. All pointers / advice appreciated.

    Read the article

  • Passing elapsed time to the update function from the game loop

    - by Sri Harsha Chilakapati
    I want to pass the time elapsed to the update() method as this would make easy to implement the animations and time related concepts. Here's my game-loop. public void gameLoop(){ boolean running = true; long gameTime = getCurrentTime(); long elapsedTime = 0; long lastUpdateTime = 0; int loops; while (running){ loops = 0; while(getCurrentTime()>gameTime && loops<Global.MAX_FRAMESKIP){ elapsedTime = getCurrentTime() - lastUpdateTime; lastUpdateTime = getCurrentTime(); update(elapsedTime); gameTime += SKIP_STEPS; loops++; } displayGame(); } } getCurrentTime() method public long getCurrentTime(){ return (System.nanoTime()/1000000); } update() method long time = 0; public void update(long elapsedTime){ time += elapsedTime; if (time>=1000){ System.out.println("A second elapsed"); time -= 1000; } } But this is printing the message for 3 seconds. Thanks.

    Read the article

  • Which is better Java programming practice for looping up to an int value: a converted for-each loop

    - by Arvanem
    Hi folks, Given the need to loop up to an arbitrary int value, is it better programming practice to convert the value into an array and for-each the array, or just use a traditional for loop? FYI, I am calculating the number of 5 and 6 results ("hits") in multiple throws of 6-sided dice. My arbitrary int value is the dicePool which represents the number of multiple throws. As I understand it, there are two options: Convert the dicePool into an array and for-each the array: public int calcHits(int dicePool) { int[] dp = new int[dicePool]; for (Integer a : dp) { // call throwDice method } } Use a traditional for loop. public int calcHits(int dicePool) { for (int i = 0; i < dicePool; i++) { // call throwDice method } } I apologise for the poor presentation of the code above (for some reason the code button on the Ask Question page is not doing what it should). My view is that option 1 is clumsy code and involves unnecessary creation of an array, even though the for-each loop is more efficient than the traditional for loop in Option 2. Thanks in advance for any suggestions you might have.

    Read the article

  • Using a array variable in a foreach loop

    - by Jess McKenzie
    I am having an issue trying to work out how to use a function variable in a foreach loop so that I can do the following but its not working. $var = array(7) { [0]=> array(3) { ["listingId"]=> int(532712629) } [1]=> array(3) { ["listingId"]=> int(532712202) } Works but not right: foreach($var as $varr) { var_dump($varr['id']); { Goal - Having the array variable as the foreach value foreach($var['id'] as $item) { if($item === $foo) { } }

    Read the article

  • How do I code a loop for my echo statement?

    - by ggg
    I get only one printed result in the foreach echo loop at the bottom of the page. <?php defined('_JEXEC') or die('Restricted access'); $db =& JFactory::getDBO(); $query0 = "SELECT * FROM `jos_ginfo` WHERE . . . LIMIT 30"; //echo $query0; $db->setQuery($query0); $ginfo = $db->loadObjectList(); //echo //$ginfo[0]; foreach($ginfo as $ginfo[$i]): {$i=0; $i++;} endforeach; echo $db->getErrorMsg(); if(empty($ginfo)){ echo "<center>No game found, try a different entry.</center>"; }else{ $pgndata = array ( $ginfo[$i]->Id); $i=0; foreach($pgndata as $ginfo[$i]->Id): //I am only getting one printed result! { echo "<a href='/index.php?option=com_publishpgn&tactical-game=".$ginfo[$i]->Id."&Itemid=78.html'>\n"; echo "".$ginfo[$i]->White." v. ".$ginfo[$i]->Black." (".$ginfo[$i]->Result.") ".$ginfo[$i]->EventDate." ECO:".$ginfo[$i]->ECO."</a><br>\n"; $i++; } endforeach; //echo "</div>"; } ?>

    Read the article

  • [PHP] Invalid argument supplied for foreach()

    - by Roberto Aloi
    It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data. $values = get_values(); foreach ($values as $value){ ... } When you feed a foreach with data that are not an array, you get a warning: Warning: Invalid argument supplied for foreach() in [...] Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings: Casting $values to array Initializing $values to array Wrapping the foreach with an if Other (please suggest)

    Read the article

  • foreach loop from multiple arrays c#

    - by Mike
    This should be a simple question. All I want to know is if there is a better way of coding this. I want to do a foreach loop for every array, without having to redeclare the foreach loop. Is there a way c# projects this? I was thinking of putting this in a Collection...? Please, critique my code. foreach (TextBox tb in vert) { if (tb.Text == box.Text) conflicts.Add(tb); } foreach (TextBox tb in hort) { if (tb.Text == box.Text) conflicts.Add(tb); } foreach (TextBox tb in cube) { if (tb.Text == box.Text) conflicts.Add(tb); }

    Read the article

  • how to run foreach loop with ternary condition

    - by I Like PHP
    i have two foreach loop to display some data, but i want to use a single foreach on basis of database result. means if there is any row returns from database then forach($first as $fk=>$fv) should execute otherwise foreach($other as $ok) should execute. i m unsing below ternary operator which gives parse error $n=$db->numRows($taskData); // databsse results <?php ($n) ? foreach ($first as $fk=>$fv) : foreach ($other as $ok) { ?> <table><tr><td>......some data...</td></tr></table> <?php } ?> please suggest me how to handle such condition via ternary operator or any other idea. Thanks

    Read the article

  • creating arrays in for loops.... without creating an endless loop that ruins my day!

    - by Peter
    Hey Guys, Im starting with a csv varible of column names. This is then exploded into an array, then counted and tossed into a for loop that is supposed to create another array. Every time I run it, it goes into this endless loop that just hammers away at my browser...until it dies. :( Here is the code.. $columns = 'id, name, phone, blood_type'; <code> $column_array = explode(',',$columns); $column_length = count($column_array); //loop through the column length, create post vars and set default for($i = 0; $i <= $column_length; $i++) { //create the array iSortCol_1 => $column_array[1]... $array[] = 'iSortCol_'.$i = $column_array[0]; } </code> What I would like to get out of all this is a new array that looks like so.. <code> $goal = array( "iSortCol_1" => "id", "iSortCol_2" => "name", "iSortCol_3" => "phone", "iSortCol_4" => "blood_type" ); </code>

    Read the article

  • C# Foreach Loop - Continue Issue

    - by Goober
    I have a problem with a continue statement in my C# Foreach loop. I want it to check if there is a blank cell in the datagridview, and if so, then skip printing the value out and carry on to check the next cell. Help appreciated greatly. Here is the code: foreach (DataGridViewRow row in this.dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Size.IsEmpty) { continue; } MessageBox.Show(cell.Value.ToString()); } }

    Read the article

  • C++ enum in foreach

    - by Spencer
    I've have a card class for a blackjack game with the following enums: enum Rank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }; enum Suit { Clubs, Diamonds, Hearts, Spades }; When I create the deck I want to write the code like this: // foreach Suit in Card::Suit // foreach Rank in Card::Rank // add new card(rank, suit) to deck I believe there is no foreach in c++. However, how do I traverse an enum? Thanks, Spencer

    Read the article

  • [C#] foreach loop corrent index

    - by Eyla
    Is there anyway to know the current run of a foreach without have to: Int32 i; foreach i++; or is that the best option i got?? Also, how can i know the maximum number of items on that loop?? What i am trying to do is update a progressbar during a foreach loop on my form Thanks This is what i got foreach (FileInfo file in DirectoryFiles) { if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (file.Attributes & FileAttributes.System) == FileAttributes.System) continue; backgroundWorkerLoadDir.ReportProgress(i, file.Name); System.Threading.Thread.Sleep(10); }

    Read the article

  • Invalid argument for foreach()

    - by johnny-kessel
    Error I'm receiving Invalid argument supplied for foreach() The offending portions is this: foreach($subs[$id] as $id2 => $data2) Strange cause I'm using the same construct elsewhere and it works fine.. I'm using it to generate sub-categories and it works but I want to get rid of the error This is more context foreach($parents as $id => $data) { if($x == 0) { $html .= "<tr width='25%' class='row2'>"; } $shtml = ""; $i = 0; ***foreach($subs[$id] as $id2 => $data2)*** { $i++; if($i == 15) { $shtml .= $this->ipsclass->compiled_templates[ 'skin_businesses' ]->portal_categories_sub_row( $id2, $data2['cat_name'], 1 ) . ""; break; } else $shtml .= $this->ipsclass->compiled_templates[ 'skin_businesses' ]->portal_categories_sub_row( $id2, $data2['cat_name'], 0 ) . ""; }

    Read the article

  • How do I code a loop for my echo statements?

    - by ggg
    <?php defined('_JEXEC') or die('Restricted access'); $db =& JFactory::getDBO(); $query0 = "SELECT * FROM `#__chesspositions` WHERE . . . . ."; //echo $query0; $db->setQuery($query0); $ginfo = $db->loadObjectList(); //echo $ginfo[0]; echo $db->getErrorMsg(); if(empty($ginfo)){ echo "<center><h2 style='color:navy'>No game found, we apologize</h2></center>"; }else{ $query1= "SELECT * FROM `#__chessmoves` WHERE Id='".$ginfo[0]->MoveDataId."'"; $db->setQuery($query1); echo $db->getErrorMsg(); $gmove = $db->loadObjectList(); } //define array; //how do I code a foreach loop (or any other type of loop) here? //I'm having trouble properly defining the array and structuring the syntax. echo "[Event \"".$ginfo[0]->Event."\"]\n"; echo "[Site \"".$ginfo[0]->Site."\"]\n"; echo "[Date \"".$ginfo[0]->Date."\"]\n"; echo "[Round \"".$ginfo[0]->Round."\"]\n"; echo "[White \"".$ginfo[0]->White."\"]\n"; echo "[Black \"".$ginfo[0]->Black."\"]\n"; echo "[Result \"".$ginfo[0]->Result."\"]\n"; echo "[ECO \"".$ginfo[0]->ECO."\"]\n"; echo "[WhiteElo \"".$ginfo[0]->WhiteElo."\"]\n"; echo "[BlackElo \"".$ginfo[0]->BlackElo."\"]\n"; echo "[Annotator \"".$ginfo[0]->Annotator."\"]\n"; echo "[SetUp \"".$ginfo[0]->SetUp."\"]\n"; echo $gmove[0]->MoveData; ?>

    Read the article

  • [Android] For-Loop Performance Oddity

    - by Jack Holt
    I just noticed something concerning for-loop performance that seems to fly in the face of the recommendations given by the Google Android team. Look at the following code: package com.jackcholt; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); loopTest(); finish(); } private void loopTest() { final long loopCount = 1228800; final int[] image = new int[8 * 320 * 480]; long start = System.currentTimeMillis(); for (int i = 0; i < (8 * 320 * 480); i++) { image[i] = i; } for (int i = 0; i < (8 * 320 * 480); i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (recompute loop limit): " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < 1228800; i++) { image[i] = i; } for (int i = 0; i < 1228800; i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (literal loop limit): " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < loopCount; i++) { image[i] = i; } for (int i = 0; i < loopCount; i++) { image[i] = i; } Log.i("loopTest", "Elapsed time (precompute loop limit): " + (System.currentTimeMillis() - start)); } } When I run this code I get the following output in logcat: I/loopTest( 726): Elapsed time (recompute loop limit): 759 I/loopTest( 726): Elapsed time (literal loop limit): 755 I/loopTest( 726): Elapsed time (precompute loop limit): 1317 As you can see the code that seems to recompute the loop limit value on every iteration of the loop compares very well to the code that uses a literal value for the loop limit. However, the code that uses a variable which contains the precomputed value for the loop limit is significantly slower than either of the others. I'm not surprised that accessing a variable should be slower that using a literal but why does code that looks like it should be using two multiply instructions on every iteration of the loop so comparable in performance to a literal? Could it be that because literals are the only thing being multiplied, the Java compiler is optimizing out the multiplication and using a precomputed literal?

    Read the article

  • How do I create a loop based off this array?

    - by dmanexe
    I'm trying to process this array, first testing for the presence of a check, then extrapolating the data from quantity to return a valid price. Here's the input for fixed amounts of items, with no variable quantity. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input type="hidden" name="measure[<?=$item->id?>][quantity]" value="1" /> Here's the inputs for variable amounts of items. <input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>"> <input class="item_mult" value="0" type="text" name="measure[<?=$item->id?>][quantity]" /> So, the resulting array is multidimensional. Here's an output: Array ( [1] => Array ( [quantity] => 1 ) [2] => Array ( [quantity] => 1 ) [3] => Array ( [quantity] => 1 ) ... [14] => Array ( [checked] => 14 [quantity] => 999 ) ) Here's the loop I'm using to take this array and process items checked off the form in the first place. I guess the question essentially boils down to how do I structure my conditional statement to incorporate the multi-dimensional array? foreach($field as $value): if ($value['checked'] == TRUE) { $query = $this->db->get_where('items', array('id' => $value['checked']))->row(); #Test to see if quantity input is present if ($value['quantity'] == TRUE) { $newprice = $value['quantity'] * $query->price; $totals[] = $newprice; } #Just return the base value if not else { $newprice = $query->price; $totals[] = $newprice; } } else { } ?> <p><?=$query->name?> - <?=money_format('%(#10n', $newprice)?></p> <? endforeach; ?>

    Read the article

  • php foreach loop help

    - by sico87
    I am working with a PHP foreach loop and I am needing it to out some specific HTML depening on which array value it is spitting out. Everytime that the foreach loop hits a $content['contentTitle'] i need it to insert a new table and then from there carry on essentially what I am what is for the loop to spit out a new table every a new contentTitle is found, but then add the rest of the data in the array as tr and td's

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >