w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How can I perfectly make a loop inside a loop which also inside another loop?
Just addressing the output part, the following code is a way to do what you described: (formatting needs a little work) #include <windows.h> #include <ansi_c.h> enum { name1, name2, name3, name_max }; char *name[name_max]={"name1","name2","name3"}; char *score1[name_max]={"12","11","1"}; char *score2[name_max]={"1","13","22"}; int main(void) { int line; printf("Number Player Name Score "); printf(" Game1 Game 2 "); for (line=name1;line < name_max;line++) { printf("%d %s %s %s ", line+1, name[line], score1[line], score2[line]); } getchar(); return 0; } With the following results:

Categories : C

JavaScript: Optimizing loop inside a loop inside a loop
Change daysOfWeek to an object: var daysOfWeek = { Mon: "Monday", Tue: "Tuesday", ... }; Then you can just access daysOfWeek[property] instead of searching daysOfWeek with a loop.

Categories : Javascript

Can a termination variable in a condition of for loop be changed inside the loop?(Java)
The string length gets calculated every loop, and your for could throw an IndexOutOfBoundsException if your string becomes too short. IMHO yours is a very bad practice, for loops are intended to make a determined number of loops and should never be stopped, also their stop condition should never be changed inside the loop, you should use a while if you don't know how many iterations you want to do. But this is my personal opinion :)

Categories : Java

for loop over Model List in MVC script and access Jquery inside loop
Looks like your selector #contactPhone select don't works cause select control also has contactPhone id. Check with .appendTo('#contactPhone'). BTW, you can use helper to populate dropdown list with your model: @{ new list = Model.worklist.Select(x => new SelectListItem { Text = x.PhoneNumber.ToString(), Value = x.PhoneNumber.ToString() }).ToList(); } @Html.DropDownListFor(model => model.PhoneNumber, list, new { id = "contactPhone" })

Categories : Javascript

Javascript, setInterval starts after while loop? how to make it start inside while loop?
What is happening is you are asking the computer to run the nested inner function once per millisecond. And you are asking this to be done ten times in a row, so by the end, the computer should be sending an alert exactly ten thousand times per second. I'm surprised it doesn't consume all the CPU and consume all memory and cause a fatal error. This will continue until you call clearInterval(), or until the window is closed. http://www.w3schools.com/jsref/met_win_setinterval.asp

Categories : Javascript

I'm considering placing a while loop inside a parent while loop that has the exact same conditions. Can I avoid this with a better object iteration?
You can return false; inside $.each() to break the loop. $(qgAnsArray[]).find('jOption').each(function(){ if($(this).attr('correct') == 'false') { $('#qg_options').append('<li><span class="qg_option">' + $(this).text() + '</span></li>'); return false; } }); If you only want the first instance of an element, you can use first(): var elem = $(qgAnsArray[]).find('jOption[correct="false"]').first();

Categories : Javascript

Make an If statement from stuff inside a foreach loop outside the loop?
As you might already experienced the construct you propose is not desired since the if statement will be executed after the loop has already ended. You can use the continue keyword to jump to the next iteration and skip fields you're not interested in. foreach ($section['fields'] as $k => $type) { if ($type['type'] != 'switch') { continue; } // do stuff } http://php.net/manual/en/control-structures.continue.php

Categories : PHP

a while loop inside a for loop not working in codeigniter view file
Here's how you can do it with just a check of the element index <div class="row"> <?php for($i=0; $i < count($headings); ): ?> <?if($i > 0 && $i%3 == 0):?> </div><!-- end of div.row --> <div class="row"> <?endif?> <div class="span4"> <?php $heading = current($headings); ?> <h2><?= key($headings); ?></h2> <p><?= $heading['description']; ?></p> <p><a class="btn" href="<?= $heading['link']; ?>">View details &raquo;</a></p> <?php next($headings); ?> <?php $i++; ?> </div> <!-- end of div.span4 --> <?php endfor; ?> </div><!-- end of div.

Categories : PHP

while loop inside a trigger to loop through all the columns of table in sql
Try this one - ALTER TRIGGER [dbo].[trgAfterUpdate] ON [dbo].[tbl_User] AFTER UPDATE AS BEGIN SET NOCOUNT ON SET XACT_ABORT ON DECLARE @DocumentUID UNIQUEIDENTIFIER DECLARE cur CURSOR FORWARD_ONLY READ_ONLY LOCAL FOR SELECT DocumentUID, ... FROM INSERTED OPEN cur FETCH NEXT FROM cur INTO @DocumentUID, ... WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @BeforeChange XML , @AfterChange XML SELECT @BeforeChange = ( SELECT * FROM DELETED WHERE [DocumentUID] = @DocumentUID FOR XML RAW, ROOT ) , @AfterChange = ( SELECT * FROM INSERTED WHERE [DocumentUID] = @DocumentUID FOR XML RAW, ROOT

Categories : Sql Server

Strange behaviour in foreach-loop inside for-loop
Your code could be a bit easier to use like this. There is no point in using the next and key operations when you're already in a foreach() loop that provides that data for you. Since the foreach loop already iterates over each element in the array, calling next() manually simply causes PHP to SKIP every other element. foreach($_POST['guest'] as $idx => $guest) { foreach($guest as $key => $val) { echo "$idx: $key => $val<br>"; } } which would echo out 1: name => foo 1: veg => ... etc... 2: name => bar etc...

Categories : PHP

Nested While loop only runs inside loop correctly
mysqli_fetch_array is similar to array_pop() in that once it fetches a result, it's not going to fetch that result again. So my guess is that your $row_wind loop is actually running through just fine, but the second time through the $row_alert loop looks for more results, finds that it's already run through them (in the loop where $row_wind = 'CT'). If you put some debug info inside the $row_wind loop but outside the $row_alert loop you should see the difference. To fix this, you'll either have to re-run the $result_user_alerts query before the inner loop, or - probably better if the inner query isn't dependent on the state - run mysqli_fetch_all() beforehand to fetch all your results for the inner loop up front, and then loop through the resulting array with your inner loop with a fore

Categories : PHP

How do I "loop" through JSON array inside foreach loop?
Use a nested loop for the answers. $tab = 0; foreach ($question as $items) { $i++; $j = 0; if ($i > 1) { $hide = ' hide'; } $this_q = "<div class='question-holder" . $hide . "' id='q" . $i . "'> <h2>" . $items->Question . "</h2> <ul class='answers' id='quiz-answers" . $i . "'> "; foreach ($items->Answers as $ans) { $tab++; $j++; $qa = "$i-$j"; $this_q .= "<li> <input tabindex='" . $tab . "' type='radio' name='txtAnswer" . $qa . "' id='txtAlt" . $qa . "' value='sdsds'> <label for='txtAlt" . $qa . "'><span>" . $ans->Answers . "</span></label> </li> ";

Categories : PHP

Avoiding loop in a loop in a loop when building a WordPress custom sitemap
Recursive functions have resolved my issue, I was able to reduce the code to the following: function check_for_children( $region_id, $children ) { if ( count($children) > 0 ) { echo '<ul class="children">'; foreach($children as $child) { echo '<li>' . $child -> post_title . '</li>'; $children = get_posts( array('category' => $region_id, 'post_type' => 'page', 'numberposts' => 100, 'post_parent' => $child -> ID, 'post_status' => 'publish', 'orderby' => 'menu_order', 'order' => 'ASC') ); check_for_children($region_id, $children); } echo '</ul>'; } else { return; } } The function calls itself until there are no longer and children, at which point it

Categories : PHP

while loop inside for loop is not showing all results but only 1
for ($x = 0; $x < $runs; $x++) { while(++$i<1001)echo$i%15?$i%5?$i%3?$i:'koukou':'roukou':'koukouroukou'," "; } should be for ($x = 0; $x < $runs; $x++) { $i=0; while(++$i<1001)echo$i%15?$i%5?$i%3?$i:'koukou':'roukou':'koukouroukou'," "; }

Categories : PHP

No for loop will run inside for loop. Testing for primes
for (int k = 0; k > 10; k++) { System.out.println(k); } k is not greater than 10, so loop will will never execute. I think what want is k<10, isn't it? for (int k = 0; k < 10; k++) { System.out.println(k); }

Categories : Java

for loop wont loop inside a function - C
When you write CheckGuess() you need to do it like this: bool CheckGuess(int guess, int nums[], int numsCount) and then call it with: if (CheckGuess(userGuess, nums, sizeof nums / sizeof *nums) Checkguess isn't "receiving" the size. Inside that function it's just a pointer.

Categories : C

Reassign loop variable inside for loop. Bug?
Because $i = 0 is not always executed. It is only executed if the account did not exist. The account is then created, so on the next pass $i is not reset to 0. You need the context around the code as well. A simplified view of just this behavior: for($i = 0; $i < $numAccounts; $i++) { $accountExistsQ = mysql_query("SELECT id FROM networkBlocks WHERE accountAddress = '".$transactions[$i]["txid"]."' ORDER BY blockNumber DESC LIMIT 0,1")or die(mysql_error()); $accountExists = mysql_num_rows($accountExistsQ); if(!$accountExists) { mysql_query("INSERT INTO `networkBlocks` (`blockNumber`, `timestamp`, `accountAddress`, `confirms`, `difficulty`) ". "VALUES ('$assoc_block', '$assoc_timestamp', '" .$transactions[$i]["txid"]. "', '" .$transactions[$i]["confirmations"]

Categories : PHP

While loop inside for loop in Matlab
With the example you showed, you have to initialize b or the while-statement cannot be evaluated when it is first called. Do it inside the for-loop to avoid false positives after the first for-iteration: n=100; for ii=1:n b = 0; while b<0.5 x(ii)=rand; b=x(ii); end end Or, without b: n=100; x = zeros(1,100); for ii=1:n while x(ii)<0.5 x(ii)=rand; end end

Categories : Matlab

Java nested for loop incrementing second loop by first for loop?
for (int i = 0; i < BRICKS_IN_BASE + (-h); i++) is really (the (-h) is simply -1*h) for (int i = 0; i < (BRICKS_IN_BASE - h); i++) due to operator precedence

Categories : Java

How to stop for loop execution untill DWR method execution completion which is inside the for loop
You can use "asynchronous pseudo-recursion" instead of a for loop, with the general pattern that I use being: var pods = [ ... ]; (function loop() { if (pods.length) { var pod = pods.shift(); // take (and remove) first element // do something with "pod" ... // recurse - put this inside a finish callback if "do something" is async loop(); } })(); // closing braces start invocation immediately where in your case, the call to loop should be the last thing inside your callback function. NB: This pattern can also be used to avoid the "browser not responding" error seen with longer running non-async operations by replacing the call to loop() with setTimeout(loop, 0). This use of setTimeout turns a synchronous recursive function into

Categories : Javascript

In a loop I'm appending a tag that alerts the loop index count. Why does it always alert the last index of the loop?
All of the callbacks refer to the same i variable in their body, which will have a value of 8 by the time any of those callbacks have been called. You need to create a variable local to each specific callback which holds the value of i at the time the callback was created: (function(j) { var cell = $('<div class="inventory-cell"></div>').mousedown(function(event) { alert("#{j} was clicked!"); }); $("#inventory-grid").append(cell); })(i); The functionally equivalent CoffeeScript would be: do (i) -> cell = $('<div class="inventory-cell"></div>').mousedown (event) -> alert "#{i} was clicked!" $("#inventory-grid").append(cell) The only difference is that do will shadow i instead of creating a new variable, but the result is the

Categories : Javascript

C++ For Loop inside a While loop
input is a double. | is a char. They are not the same thing. So cin fails and your while loop is not entered. To do what you are attempting, you need to input the data as a string first, check its value for |, and if not a match then convert it to a double for further processing.

Categories : C++

for loop inside a while loop
The reason it is executing the for loop just one time is that you are exhausting the buffer you created for your "words.txt" file during the first iteration of the for loop. If you want to go through the words in that file multiple times you need to reopen it each time (which, as you noted, creates a lot of overhead). Alternatively, read that file into a list and then run the while/for-loop structure that list. I.E. fin= open('words.txt') wordList = fin.readlines() u=97 v=97 ... for line in wordList ...

Categories : Python

PHP for loop inside a while loop
You don't need a for loop. You just need a counter variable (I named it $i here) you increment each time you enter the while loop: $i = 0; while($avr = mysql_fetch_array($rating)) { ?> <li class="movie"><?php echo ++$i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li> <?php // Increment & Insert ---------^ }

Categories : PHP

Foreach loop inside foreach loop (Java)
You have to assign roles in the outer loop (so that it varies when org varies) for(TOrganization org : organizations) { message.append(" - " + org.getName()+ " "); // like this, you adapt ;) roles = org.getRoles(); for(TRole role : roles) { if(role.getOrganization().equals(org)) { message.append(" - " + role.getName()+ " "); } } } edit: you should make Set<TRole> roles = new LinkedHashSet<TRole>(); member of TOrganization IMO

Categories : Java

How can i break my continuous loop, if a input is received from user side and continue with the loop
These language constructs are made especially for loops, maybe it will help: break - breaks out of the loop, continue - goes to the next looping procedure.

Categories : PHP

R Optimise a while loop nested in a for loop to introduce missing values in a dataframe
I am not sure if this is what you are looking for: library(missForest) data1<-iris[1:70,1:4] for(i in 1:28){ data1[i,]<-prodNA(mydata[i,],noNA =0.10) } table(is.na(data1)) n<-10 data2<-do.call("rbind", replicate(n, data1, simplify=FALSE)) table(is.na(data2)) data3<-prodNA(data2,noNA=0.55) > table(is.na(data3)) FALSE TRUE 1133 1667

Categories : R

Would compiler optimize conditional statement in loop by moving it ouside the loop?
That would greatly depend on how big /* code 1 */ is. If it is very small, it might. But if it is anything above a few lines, it most probably won't. Duplicating a large amount of code for every single if would have terrible effects on the performance. In fact, that may happen with very aggressive optimization and certainly not just with -O. From the man page of gcc (emphasis mine): -O -O1 ... With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time. So reducing code is also part of optimization. -O2 Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to -O, this option increases both compilation time and the

Categories : C

Python 3+ - for in range loop, multiply, product, list NOT using mul or lambda or for in loop
The idea is pretty much the same as for in. Note that you don't need to make a variable from the list length, also you don't need to specify a start for the range(), it's 0 by default. def prod(L): p = 1 for i in range(len(L)): p *= L[i] return p print(prod([1,2,3,4])) # prints 24

Categories : Python

how to transfer the control to outer loop from inner loop after some conds are checked and some operations are done?
You can use break with label. Here is example from Java tutorial: search is label here. class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found " + searchfor + " at "

Categories : Java

Objective-C >> Using for-in Loop >> Making the Loop Enter Only if the Object is of a Certain Type
Just check for the correct class yourself, by using isKindOfClass: for (MYObject* myObj in simpleArray) { if (![myObj isKindOfClass:[MYObject class]]) { // wrong class. continue to next object. continue; } sumNums += myObj.myNum; }

Categories : Objective C

Draw Kinetic.Shape in for-loop - var i of for-loop isn't taken properly in drawFunc()
You can try something like this. By adding the layers using a function the value passed to the createLayer function is saved with each Kinetic.Shape object that's created through closures. function createLayer(nbr){ layer.add(new Kinetic.Shape({ x: 0, y: 0, width: 400, height: 400, drawFunc: function(canvas){ console.log(nbr); var ctx = canvas.getContext(); ctx.beginPath(); ctx.fillStyle = 'black'; ctx.fillRect(10, nbr*30+2, 200, 30); ctx.closePath(); ctx.fill(); } })); } for (var i = 0; i < 3; i++){ createLayer(i); }

Categories : HTML

Refactoring/Vectorize a simple for loop (example data and loop included)
Aren't you just doing sif <- matrix(s, ncol=N, byrow=T) Edit: You have to be a bit careful if the count of elements of the new matrix do not match the old one exactly. Then, the following will do: sif <- matrix(s[1:(round(length(s)/N)*N)], ncol=N, byrow=T) I did a careful computation, calling my result sif2. What I got: > max(abs(sif[1:9999,1:100]-sif2[1:9999,1:100])) [1] 0 However, > sif[10000,] [1] 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 10000 ... Of course, as you never fill the last row of your data. Is this intended? If yes, you may easily change my result by sif2[nrow(sif2), ] <- nrow(sif2) There is no need to compare performace, but for the sake of completeness: User System

Categories : R

Django nested for loops: Is it possible to use the result from the first loop within the definition of the second for loop?
I would say that the collection should look more like sectList = {"Id": 1, "Section": "Home", "Identifier": {"Id": 1, "Title": "Home", "Url": "home/","Id": 2, "Title": "My Account", "Url": "account/","Id": 3, "Title": "Full List", "Url": "fullList/",}} You see - "Identifier": "homeList" is not really a link to your second list. Its just a prop. name and value.

Categories : Python

For Loop/Each Loop variable storage and comparison (jQuery or Javascript
you can use index in $.each() like $('.searchMe').each(function(index){ var id = $(this); sortUp += 1, sortDown -= 1; if (test) {// don't know what is test, let it is predefined id.attr("name", sortUp);// no need to add "" } else { id.attr("name", sortDown); } if ($('.searchMe').eq(index-1).length && id.attr("name") > $('.searchMe').eq(index-1).attr("name") ) { id.insertBefore($('.searchMe').eq(index-1)); } }); Or Alternatively you can define lastid like var lastId='';// let it be global $('.searchMe').each(function(index){ var id = $(this); sortUp += 1, sortDown -= 1; if (test) {// don't know what is test, let it is predefined id.attr("name", sortUp);// no need to add "" } else { id.attr("name", sortD

Categories : Javascript

Querying database in a loop, loop with a sleep, or separate request
I'll take a stab at why programmers consider sleep bad in a loop, which seems to be the heart of your question. Short answer, yes you can use sleep. Why would you not then? What you ideally want is to do some work when data becomes available in your database. For this, if you can get notified when data becomes available then you've done the least amount of work. There are multiple way to achieve this in programming: webhooks in the HTTP world, locks / semaphores, callbacks, and events / observers are a few paradigms. Another cited reason is race conditions, which I will let you read about. Since the database is doing things atomically for you, this is not so much of a worry. However, in the ideal stateless world that is HTTP, you can't lock, and sometimes you simply can't get events

Categories : PHP

Why the for loop counter doesn't get destroyed after exiting the loop in javascript?
This is because the JavaScript engine will move ("hoist") the variable decalaration to the top of the function no matter where it is declared inside the function1. JavaScript does not have block scope. { //Some code for(var i=0;i<5;i++){} alert(i); //Some code } Is equivalent to: { var i; //.. some code for(i=0;i<5;i++){} alert(i); } 1 Unless it's the exception being caught with a catch clause; that variable is scoped to catch block. Update For defining block scope variables ecmascript 6 specs (javascript 1.7) introduces let. Currently this will work only in latest version of FireFox browser and in consensus stage. <script type="application/javascript;version=1.7"> //Some code for (let i = 0; i < 10; i++) { alert(i); // 1,

Categories : Javascript

where to put a while loop in a system tray application so that loop starts with the app
Thank you Hans! I added a new "Component Class" with WM_DEVICECHANGE and it is working fine. Just in case anyone needs this info: If a function needs to be called as soon as the Windows Forms App starts (Systray app in my case), the respective function can be called after the call to "InitializeComponent()" function. Though it is clearly mentioned "TODO: Add the constructor code here", still a beginner (like me) has inhibitions regarding "Where to put this Function Call??" Hope this helps somebody..

Categories : Visual C++

parallelize nested loop in OpenMP and do inner loop with more thread
Regarding parallelism introduction, it's common to say that the coarser level is better, so if you can add parallel directive at a coarse level that scale well why would you also add nested parallelism ? so based on what can be run concurrently i would write the main like that: int main() { //first_for #pragma parallel for for(int y=0; y< height; y++) { //second_for and third_for for(int x=0; x< width-1; x++) { func1(); func2(); } } //fourth_for #pragma parallel for for(int x=0; x<width; x++) { //fifth_for and //sixth_for for(int y=0; y< height-1; y++) { func3(); func4(); } } return 0; } we increase the work to do per line and per column by merging the 2

Categories : C++

Update upper limit /bound of for loop, while in for loop
Your code sample should have next i but it will only loop once because the upper-limit will already have been exceeded. If you need to change the upper-bound within the loop then I recommend that you use a Do..Loop instead; this will be far easier to maintain and control.

Categories : Excel



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.