Search Results

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

Page 29/482 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • C++ Loop - Need variable to accumulate sum

    - by user1780064
    I'm writing a program to ask the user to enter a value between 5 and 21 (inclusive). If the number entered is not in this range, it prints, "Please try again". If the number is within the range, I need to take that number, and print the sum of all the numbers from 1 to the value entered. So if the user entered "7", the sum would be "28". I successfully wrote the first loop, in the case of the number not being within the range, but cannot figure out how to run the second loop- whether to use a while, do-while, or for loop. Please advise. #include <iostream> int main () { int uservalue; int count; int sum; //Prompt user for input do { cout << "Enter a value from 5 to 21: "; cin >> uservalue; if (uservalue < 5 || uservalue > 21) cout << "Value out of range. Try again..." << endl; } while (uservalue < 5 || uservalue > 21); cout << endl; //Loop to accumulate sum for (count = 1, count < uservalue, count++;) { sum = uservalue + count; if (uservalue <= 5 || uservalue <= 21) cout << the sum is " << sum << endl; } return 0; }

    Read the article

  • Python & Pygame: Updating all elements in a list under a loop during iteration

    - by Unit978
    i am working on a program in Python and using Pygame. this is what the basic code looks like: while 1: screen.blit(background, (0,0)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN and event.key == K_c: circle_create = True circle_list.append(Circle()) if event.type == MOUSEBUTTONDOWN and circle_create == True: if clicks == 0: circle_list[i].center() clicks += 1 if event.type == MOUSEMOTION and clicks == 1 and circle_create == True: circle_list[i].stretch() these if statements are under the while loop not the for loop since they dont require input from the user if circle_create == True: circle_list[i].draw_circle() if clicks == 2: clicks = 0 i += 1 circle_create = False pygame.display.update() what i want to do is have the object's function of draw_circle() to be constantly updated by the loop so that the drawn circle is shown for all objects in the list, but since the list is iterated it updates the new object added and the objects already appended are not updated. The program, works, it draws the circles upon user input but the update problem is the only issue i need to solve. Is there any possible way to have all elements in the list of objects being updated by the while loop? i have tried for many days and i have not been able to find a good solution. any ideas are appreciated. Thanks

    Read the article

  • for loop vs std::for_each with lambda

    - by Andrey
    Let's consider a template function written in C++11 which iterates over a container. Please exclude from consideration the range loop syntax because it is not yet supported by the compiler I'm working with. template <typename Container> void DoSomething(const Container& i_container) { // Option #1 for (auto it = std::begin(i_container); it != std::end(i_container); ++it) { // do something with *it } // Option #2 std::for_each(std::begin(i_container), std::end(i_container), [] (typename Container::const_reference element) { // do something with element }); } What are pros/cons of for loop vs std::for_each in terms of: a) performance? (I don't expect any difference) b) readability and maintainability? Here I see many disadvantages of for_each. It wouldn't accept a c-style array while the loop would. The declaration of the lambda formal parameter is so verbose, not possible to use auto there. It is not possible to break out of for_each. In pre- C++11 days arguments against for were a need of specifying the type for the iterator (doesn't hold any more) and an easy possibility of mistyping the loop condition (I've never done such mistake in 10 years). As a conclusion, my thoughts about for_each contradict the common opinion. What am I missing here?

    Read the article

  • delay loop output in C++

    - by itachisxeyes
    I have a while loop that runs in a do while loop. I need the while loop to run exactly every second no faster no slower. but i'm not sure how i would do that. this is the loop, off in its own function. I have heard of the sleep() function but I also have heard that it is not very accurate. int min5() { int second = 00; int minute = 0; const int ZERO = 00; do{ while (second <= 59){ if(minute == 5) break; second += 1; if(second == 60) minute += 1; if(second == 60) second = ZERO; if(second < 60) cout << "Current Time> "<< minute <<" : "<< second <<" \n"; } } while (minute <= 5); }

    Read the article

  • iphone basic game loop

    - by Mrigank Gupta
    I am little confused with my Opengl game loop. as I am skipping touch events some times. My game loop is some thing like this.. I have ScreenManager which draw and update all game screens who so ever has control.In update I am checking input of all screen also. if input state changes, then whichever screen has control, consume touches. EaglView draw update | | ScreenManager.draw ScreenManager.update -> handle input stack ___________ ___________ of ___________ ___________ screen ___________ ___________ Problem comes.. I am changing input state as touch begun and end methods called. but sometimes In my game loop both touchbegun/end methods get called between two updates and I am missing events. I guess approach is not good. can you guys share your approach to this problem.

    Read the article

  • Get page permalink and title outside the loop in wordpress

    - by Aakash Chakravarthy
    Hello, How to Get page permalink and title outside the loop in wordpress. I have a function like function get_post_info(){ $post; $permalink = get_permalink($post->ID); $title = get_the_title($post->ID); return $post_info('url' => $permalink, 'title' => $title); } when this function called within the loop, it returns the post's title and url. When it is called outside the loop. It is not returning the current page's title and url. When called in home page it should return the home page's title and url How to get like this ? instead this function returns the latest posts title and url

    Read the article

  • python: sorting

    - by nabizan
    hi im doing a loop so i could get dict of data, but since its a dict it's sorting alphabetical and not as i push it trought the loop ... is it possible to somehow turn off alphabetical sorting? here is how do i do that data = {} for item in container: data[item] = {} ... for key, val in item_container.iteritems(): ... data[item][key] = val whitch give me something like this data = { A : { K1 : V1, K2 : V2, K3 : V3 }, B : { K1 : V1, K2 : V2, K3 : V3 }, C : { K1 : V1, K2 : V2, K3 : V3 } } and i want it to be as i was going throught the loop, e.g. data = { B : {K2 : V2, K3 : V3, K1 : V1}, A : {K1 : V1, K2 : V2, K3 : V3}, C : {K3 : V3, K1 : V1, K2 : V2} }

    Read the article

  • Loop doesn't update listboxes until it is done iterating

    - by Justen
    I have a loop that takes file name from a listbox, performs a system() call, then moves that filename to another listbox. Problem is, it doesn't move the filenames over one at a time, but waits until the entire loop is finished and moves them all at once. What would I do to get it to perform how I want it to? the loop: for each( String^% file in filename ) { int x = convert( file ); lbComplete->Items->Add( lbFiles->Items[0] ); // place the completed file lbFiles->Items->Remove( lbFiles->Items[0] ); // in the other listbox } The function convert() that contains the system call: int convert( String^ file ) { std::stringstream ss; std::string dir, fileAddress, fileName, outputDir; ... return system( ss.str().c_str() ); }

    Read the article

  • java looping - declaration of a Class outside / inside the loop

    - by lisak
    when looping, for instance: for ( int j = 0; j < 1000; j++) {}; and I need to instantiate 1000 objects, how does it differ when I declare the object inside the loop from declaring it outside the loop ?? for ( int j = 0; j < 1000; j++) {Object obj; obj =} vs Object obj; for ( int j = 0; j < 1000; j++) {obj =} It's obvious that the object is accessible either only from the loop scope or from the scope that is surrounding it. But I don't understand the performance question, garbage collection etc. What is the best practice ? Thank you

    Read the article

  • What does the `forall` keyword in Haskell/GHC do?

    - by JUST MY correct OPINION
    I've been banging my head on this one for (quite literally) years now. I'm beginning to kinda/sorta understand how the foreach keyword is used in so-called "existential types" like this: data ShowBox = forall s. Show s => SB s (This despite the confusingly-worded explanations of it in the fragments found all around the web.) This is only a subset, however, of how foreach is used and I simply cannot wrap my mind around its use in things like this: runST :: forall a. (forall s. ST s a) -> a Or explaining why these are different: foo :: (forall a. a -> a) -> (Char,Bool) bar :: forall a. ((a -> a) -> (Char, Bool)) Or the whole RankNTypes stuff that breaks my brain when "explained" in a way that makes me want to do that Samuel L. Jackson thing from Pulp Fiction. (Don't follow that link if you're easily offended by strong language.) The problem, really, is that I'm a dullard. I can't fathom the chicken scratchings (some call them "formulae") of the elite mathematicians that created this language seeing as my university years are over two decades behind me and I never actually had to put what I learnt into use in practice. I also tend to prefer clear, jargon-free English rather than the kinds of language which are normal in academic environments. Most of the explanations I attempt to read on this (the ones I can find through search engines) have these problems: They're incomplete. They explain one part of the use of this keyword (like "existential types") which makes me feel happy until I read code that uses it in a completely different way (like runST, foo and bar above). They're densely packed with assumptions that I've read the latest in whatever branch of discrete math, category theory or abstract algebra is popular this week. (If I never read the words "consult the paper whatever for details of implementation" again, it will be too soon.) They're written in ways that frequently turn even simple concepts into tortuously twisted and fractured grammar and semantics. (I suspect that the last two items are the biggest problem. I wouldn't know, though, since I'm too much a dullard to comprehend them.) It's been asked why Haskell never really caught on in industry. I suspect, in my own humble, unintelligent way, that my experience in figuring out one stupid little keyword -- a keyword that is increasingly ubiquitous in the libraries being written these days -- are also part of the answer to that question. It's hard for a language to catch on when even its individual keywords cause years-long quests to comprehend. Years-long quests which end in failure. So... On to the actual question. Can anybody completely explain the foreach keyword in clear, plain English (or, if it exists somewhere, point to such a clear explanation which I've missed) that doesn't assume I'm a mathematician steeped in the jargon?

    Read the article

  • Fibonacci Sequence using loop and recur

    - by AdamJMTech
    I am doing the Project Euler challenge in Clojure and I want to find the sum of all the even numbers in a fibonacci sequence up to a certain number. The code for a function that does this is below. I know there are quicker and easier ways of doing this, I am just experimenting with recursion using loop and recur. However the code doesn't seem to work it never returns an answer. (defn fib-even-sum [upto] (loop [previous 1 nxt 1 sum 0] (if (or (<= upto 1) (>= nxt upto)) sum) (if (= (mod nxt 2) 0) (recur nxt (+ previous nxt) (+ sum nxt)) (recur nxt (+ previous nxt) sum)))) I was not sure if I could do recur twice in the same loop or not. I'm not sure if this is causing the problem?

    Read the article

  • Python Beginner: Selective Printing in loops

    - by Jonathan Straus
    Hi there. I'm a very new python user (had only a little prior experience with html/javascript as far as programming goes), and was trying to find some ways to output only intermittent numbers in my loop for a basic bicycle racing simulation (10,000 lines of biker positions would be pretty excessive :P). I tried in this loop several 'reasonable' ways to communicate a condition where a floating point number equals its integer floor (int, floor division) to print out every 100 iterations or so: for i in range (0,10000): i = i + 1 t = t + t_step #t is initialized at 0 while t_step is set at .01 acceleration_rider1 = (power_rider1 / (70 * velocity_rider1)) - (force_drag1 / 70) velocity_rider1 = velocity_rider1 + (acceleration_rider1 * t_step) position_rider1 = position_rider1 + (velocity_rider1 * t_step) force_drag1 = area_rider1 * (velocity_rider1 ** 2) acceleration_rider2 = (power_rider2 / (70 * velocity_rider1)) - (force_drag2 / 70) velocity_rider2 = velocity_rider2 + (acceleration_rider2 * t_step) position_rider2 = position_rider2 + (velocity_rider2 * t_step) force_drag2 = area_rider1 * (velocity_rider2 ** 2) if t == int(t): #TRIED t == t // 1 AND OTHER VARIANTS THAT DON'T WORK HERE:( print t, "biker 1", position_rider1, "m", "\t", "biker 2", position_rider2, "m"

    Read the article

  • postgresql syntax while exists loop

    - by veilig
    I'm working at function from Joe Celkos book - Trees and Hierarchies in SQL for Smarties I'm trying to delete a subtree from an adjacency list but part my function is not working yet. WHILE EXISTS –– mark leaf nodes (SELECT * FROM OrgChart WHERE boss_emp_nbr = -99999 AND emp_nbr > -99999) LOOP –– get list of next level subordinates DELETE FROM WorkingTable; INSERT INTO WorkingTable SELECT emp_nbr FROM OrgChart WHERE boss_emp_nbr = -99999; –– mark next level of subordinates UPDATE OrgChart SET emp_nbr = -99999 WHERE boss_emp_nbr IN (SELECT emp_nbr FROM WorkingTable); END LOOP; my question: is the WHILE EXISTS correct for use w/ postgresql? I appear to be stumbling and getting caught in an infinite loop in this part. Perhaps there is a more correct syntax I am unaware of.

    Read the article

  • Assigning values to variable WHILE loop

    - by Milaan
    Hi! I have a WHILE loop that loops through a table as long as $i is less than 10. I want this loop to assign the INNERHTML of each cell to a variable. So that I can use it later on to process the information (the loop is because you can choose if it has to take first 3 or first 10 cells). But how do I assign every innerHTML to a different variable? I'm sure there has to be an easy way. But google couldn't get me a good answer. Thanks in advance! Milaan

    Read the article

  • Two BlockingQueue in the same endless loop?

    - by DrDol
    I have a thread, that processes incomming messages (endless loop). For this, I use a BlockingQueue (Java), which works as quite nice. Now, I want to add a second processor in the same Class oder method. The problem now is, that in the endless loop i have this part newIncomming = this.incommingProcessing.take(); This part blocks if the Queue is empty. I'm looking for a solution to process to queues in the same class. The second queue can only processed, it some data is coming in for the first Queue. Is there a way to handle tow blocking queues in the same endless loop?

    Read the article

  • How to make if loop in grails?

    - by user3569696
    I'm beginner in Grails, please help. I have this in my gsp <div class="right66"> <g:select class="time_pick" name="pick_day" placeholder="" from="${['Dani', 'Sati', 'Minute']}" valueMessagePrefix="book.category"/> </div> In translation: Dani=Days, Sati= Hours, Minute= Minutes. I need to save data in minutes but User have privilege to choose will his input be in minutes, days or hours. So i have to do if loop. I now how if loop works but i don't know how to wite it in grails. I was thinking something like this: n=1 if(params.type=Dani){ n= 3600 }else if(params.type=Sati) { n=60 } def minute=params.minute*n but how to call that choosen input "Dani"? I can't write Params.type=Dani. Does if loop go in controller in my case?

    Read the article

  • How to replace for-loops with a functional statement in C#?

    - by Lernkurve
    A colleague once said that God is killing a kitten every time I write a for-loop. When asked how to avoid for-loops, his answer was to use a functional language. However, if you are stuck with a non-functional language, say C#, what techniques are there to avoid for-loops or to get rid of them by refactoring? With lambda expressions and LINQ perhaps? If so, how? Questions So the question boils down to: Why are for-loops bad? Or, in what context are for-loops to avoid and why? Can you provide C# code examples of how it looks before, i.e. with a loop, and afterwards without a loop?

    Read the article

  • C++ Sentinel/Count Controlled Loop beginning programming

    - by Bryan Hendricks
    Hello all this is my first post. I'm working on a homework assignment with the following parameters. Piecework Workers are paid by the piece. Often worker who produce a greater quantity of output are paid at a higher rate. 1 - 199 pieces completed $0.50 each 200 - 399 $0.55 each (for all pieces) 400 - 599 $0.60 each 600 or more $0.65 each Input: For each worker, input the name and number of pieces completed. Name Pieces Johnny Begood 265 Sally Great 650 Sam Klutz 177 Pete Precise 400 Fannie Fantastic 399 Morrie Mellow 200 Output: Print an appropriate title and column headings. There should be one detail line for each worker, which shows the name, number of pieces, and the amount earned. Compute and print totals of the number of pieces and the dollar amount earned. Processing: For each person, compute the pay earned by multiplying the number of pieces by the appropriate price. Accumulate the total number of pieces and the total dollar amount paid. Sample Program Output: Piecework Weekly Report Name Pieces Pay Johnny Begood 265 145.75 Sally Great 650 422.50 Sam Klutz 177 88.5 Pete Precise 400 240.00 Fannie Fantastic 399 219.45 Morrie Mellow 200 110.00 Totals 2091 1226.20 You are required to code, compile, link, and run a sentinel-controlled loop program that transforms the input to the output specifications as shown in the above attachment. The input items should be entered into a text file named piecework1.dat and the ouput file stored in piecework1.out . The program filename is piecework1.cpp. Copies of these three files should be e-mailed to me in their original form. Read the name using a single variable as opposed to two different variables. To accomplish this, you must use the getline(stream, variable) function as discussed in class, except that you will replace the cin with your textfile stream variable name. Do not forget to code the compiler directive #include < string at the top of your program to acknowledge the utilization of the string variable, name . Your nested if-else statement, accumulators, count-controlled loop, should be properly designed to process the data correctly. The code below will run, but does not produce any output. I think it needs something around line 57 like a count control to stop the loop. something like (and this is just an example....which is why it is not in the code.) count = 1; while (count <=4) Can someone review the code and tell me what kind of count I need to introduce, and if there are any other changes that need to be made. Thanks. [code] //COS 502-90 //November 2, 2012 //This program uses a sentinel-controlled loop that transforms input to output. #include <iostream> #include <fstream> #include <iomanip> //output formatting #include <string> //string variables using namespace std; int main() { double pieces; //number of pieces made double rate; //amout paid per amount produced double pay; //amount earned string name; //name of worker ifstream inFile; ofstream outFile; //***********input statements**************************** inFile.open("Piecework1.txt"); //opens the input text file outFile.open("piecework1.out"); //opens the output text file outFile << setprecision(2) << showpoint; outFile << name << setw(6) << "Pieces" << setw(12) << "Pay" << endl; outFile << "_____" << setw(6) << "_____" << setw(12) << "_____" << endl; getline(inFile, name, '*'); //priming read inFile >> pieces >> pay >> rate; // ,, while (name != "End of File") //while condition test { //begining of loop pay = pieces * rate; getline(inFile, name, '*'); //get next name inFile >> pieces; //get next pieces } //end of loop inFile.close(); outFile.close(); return 0; }[/code]

    Read the article

  • string parse and replace in for loop

    - by reffer
    i have a string that looks like this - "1AL||9CA||34CO||196WY||..." i want to use a for loop or while loop, in which if i have an integer, it should parse this string and delete the value matching that integer. example for above string string = "1AL||9CA||34CO||196WY||..." integer = 34 for ... loop new string = "1AL||9CA||196WY||..." As you can see the integer matched the integer 34 and deleted from one delimeter "||" to th next one. how can i do this?

    Read the article

  • Strange behavior of for loop in scheduler_tick

    - by EpsilonVector
    I'm working on Linux kernel 2.4 (homework) and I inserted the following code into the scheduler_tick function: if (unlikely(rt_task(p)) || (p->policy==SCHED_PROD && p->time_ran>=p->process_expected_time)) { /* * RR tasks need a special form of timeslice management. * FIFO tasks have no timeslices. */ if ((p->policy == SCHED_RR || /*change*/p->policy==SCHED_PROD) && !--p->time_slice) { /*changes*/ if (p->policy == SCHED_PROD){ for (i=0; i<5000; i++){ printk("I'm leeching off SCHED_RR code! %d\n", i); } } /*end changes*/ The addition was added for debugging purposes. For some reason this causes very weird behavior: when a SCHED_PROD process triggers this code (and consequently the loop that follows) the loop counts to about 4600 normally, but then goes back to 4600 each time it counts to 4800, and gets stuck in an infinite loop. What's going on?? EDIT: The i variable is my own.

    Read the article

  • Bash loop command until file contains n duplicate entries (lines)

    - by Andrew
    Hello, I'm writing a script and I need to create a loop that will execute same commands until file does contain a specified number of duplicate entries. For example, with each loop I will echo random string to file results. And I want loop to stop when there are 10 lines of of the same string. I thought of something like while [ `some command here (maybe using uniq)` -lt 10 ] do command1 command2 command3 done Do you have any idea how can this problem be solved? Using grep can't be done since I don't know what string I need to look for. Thank you for your suggestions.

    Read the article

  • For-Each and Pointers in Java

    - by John
    Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code: ArrayList<String> arr = new ArrayList<String>(); //... fill with some values (doesn't really matter) for(String t : arr) { t = " some other value "; //hoping this would change the actual array } for(String t : arr) { System.out.println(t); //however, I still get the same array here } My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer. All comments are appreciated! Even if you say I should just suck it up and use a different construct.

    Read the article

  • Erlang message loops

    - by Roger Alsing
    How does message loops in erlang work, are they sync when it comes to processing messages? As far as I understand, the loop will start by "receive"ing a message and then perform something and hit another iteration of the loop. So that has to be sync? right? If multiple clients send messages to the same message loop, then all those messages are queued and performed one after another, or? To process multiple messages in parallell, you would have to spawn multiple message loops in different processes, right? Or did I misunderstand all of it?

    Read the article

  • border highlighting loop with jquery

    - by Tek
    I'm having trouble coming up with a loop that changes the border color of an image from black to yellow and yellow to black over x seconds. Then applying an interrupt to the loop when the image gets clicked on. I don't know where to start, can someone point me in the right direction? I think I may be using the wrong tools to properly write this. Here's what I've come up so far, though if there's a better way to write this, do share! for( i = 100; i >= 0; i--) { $("#imgid").css("border-color", 'rgb(' + i + '%,' + i + '%,0)'); } I'm having trouble picturing how I could combine two loops so that I can also count upwards as well so that it will turn into yellow and back to black. I also don't know how to go about controlling the amount of time it takes for that loop to execute and creating an interrupt when #imigid is clicked. Which is where I'm not sure how to write.

    Read the article

  • a nicer way to create structs in a loop

    - by sandra
    Hi guys, I haven't coded in C++ in ages. And recently, I'm trying to work on something involving structs. Like this typedef struct{ int x; int y; } Point; Then in a loop, I'm trying to create new structs and put pointers to them them in a list. Point* p; int i, j; while (condition){ // compute values for i and j with some function... p = new Point; p* = {i, j}; //initialize my struct. list.append(p); //append this pointer to my list. } Now, my question is it possible to simplify this? I mean, the pointer variable *p outside of the loop and calling p = new Point inside the loop. Isn't there a better/nicer syntax for this?

    Read the article

< Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >