Run a while() function n times in gdb - gdb

How would I go about running a while loop in C to say N number of times?
For example, I reach this function and then I want to run the while() block 5 times.
// while there are customers
while (customers_length)
{
// check if there are customers waiting
if (index == initial_customers_length)
customers_are_waiting = 0;
// increment one hour
sum++;
// for every cashier subtract one hour
for (i = 0; i < n; i++)
{
cashiers[i].how_many_hours--;
// if cashier has no customers and no customers waiting reset to 0;
if (cashiers[i].how_many_hours < 0)
cashiers[i].how_many_hours = 0;
}
// if a cashier is free and there are no customers waiting, allocate next customer
for (i = 0; i < n; i++)
{
if (!cashiers[i].how_many_hours && customers_are_waiting)
{
cashiers[i].how_many_hours = customers[index];
customers_length--;
// queue next customer in line
index++;
}
if (!cashiers[i].how_many_hours)
customers_length--;
}
}
What's the command for that in gdb?

I want to run the while() block 5 times.
Set a break point on the first if statement inside the loop. Then use ignore $bpnum 5 and continue.
GDB will stop on the if statement breakpoint on 6th iteration through the loop.

Related

C++ Printing Odd numbers instead of Prime Numbers

I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:
Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.
I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!
int main() {
for (int i=2; i <=10; i++){
for (int j=2; j<=i; j++){
if (i%j==0 && j!=i) {
break;
}
else {
cout<< i <<endl;
break;
}
}
}
}
In addition to Sumit Jindal's answer inner for loop can be done by this way as well:
for(int j=2; j*j<=i ; j++)
If we think about every (x,y) ordered pair that satisfies x*y = i, maximum value of x can be square root of i.
The problem lies in the if-else branch. Your inner loop will be run exactly once because it will break out of the inner loop as a result of your if else branch.
When you first enter the inner loop the value of j is 2. Your condition will test if variable i is divisible by 2. If it is it breaks. Other wise (your else branch) will print the value of i and breaks out.
Hence printing odd numbers.
Break out of the inner loop and check whether j equals i in outer loop. You have to make j available for outer loop.
Your print statement is within the inner loop, and it should not be - it's only a prime if you run all the way through the inner loop without finding a divisor.
As a second point, you only need to check for divisors up to the square root of i, not all the way up to i.
You are breaking the inner loop after the first iteration itself, which is checking if the number(ie i) is different from j and is divisible by 2 or not (since j=2 for the first iteration)
I am getting 2,3,5,7,9 as my output
This is because every odd number fails the if and is printed in else condition
A minor correction in your code, adding a flag. Also you don't need to run the inner loop i times, infact only i/2 times is sufficient. This is simple mathematics, but will save significant number of CPU cycles (~5000 iterations lesser in your case)
#include <iostream>
int main()
{
int n = 10;
for(int i=2; i<=n; i++){
bool isPrime = true;
for(int j=2; j<=i/2; j++){
if(i!=j && i%j==0){
isPrime = false;
break;
}
}
if(isPrime)
std::cout << i << " ";
}
return 0;
}
Another version, if you don't mind output in reverse order.
int n = 10;
for (int i = n; i > 1; --i)
{
int factorCount = 0;
for (int j = 2; j <= n; ++j)
{
if (i % j == 0)
factorCount++;
if (factorCount > 1)
break;
}
if (factorCount == 1)
cout << i << endl;
}
int main() {
for (int i = 2; i <= 100; i++) {
for (int j = 2; j < i; j++) {
if (i%j == 0)
break;
if (j==i-1) // means has never run previous if blog
cout << i << endl;
}
}
return 0;
}

How to end a loop early without break

for (int att = 1; att < 11; att++)
{
<body>;
//break will completely finish running the program
}
I'm making a CodeBreaker(Mastermind) game, and I'm having trouble with ending a loop earlier than it needs to at less than 11, and then set the loop back to the initialization state of att = 1.
att stands for "attempts". The user can guess a randomly generated code up to a maximum of 10 times. Once the user guesses the correct code in less than 10 attempts, I want to prompt the user to play again and generate a new random code. But the loop shown above is still running.
How can I end the loop early, but still continue running the program? Majority of the program depends on this one loop, so break will completely stop it running.
To set the loop back to the initialization state of att = 1, you can use continue:
for (int att = 1; att < 11; att++)
{
if(you_want_to_set_loop_back) {
att = 1;
continue; //It will begin the loop back with att=1, but if any other variable is modified, they will remain as it is (modified).
}
}
OR
You can write your loop in a function with all the variable that you want at their initial value. And keep calling this function as long as you want. To break out the loop, use break and return from function or directly return from the loop instead of breaking it.
You could do something like:
while(true){
for (int att = 1; att < 11; att++)
{
<body>;
//game, and when it finishes
break;
}
//Asks player if he wants to continue, if not then break again
}
How about a while-loop around the for-loop?
while(programRunning){
for (int att = 1; att < 11; att++)
{
<body>;
if(answer==correct){
att = 12; // ends the for-loop
}
}
if(gameOver){
programRunning = false; // unless you want to end the game, starts the for-loop from att = 1
}
}
I think you might try in following way:
bool bQuitGame = false;
while(!bQuitGame)
{
for(att = 1; att < 10; ++att)
{
if(you want to only quit "for" but stay in "while")
{
<code...>
break;
}
else if(you want to quit "while")
{
<code...>
bQuitGame = true;
break
}
else if(you want to start the next iteration in "for")
{
<code..>
continue;
}
else //you want to stay in "for"
{
<code...>
}
}
}
It seems your problem can be solved by simple nested loops like these :
while(!success){
for (int att = 1; att < 11; att++){
<body>;
if(answer is correct){
success = true;
break;
}
//break will completely finish running the program
}
}

Displaying sentence array outside of for loop

I'm having problem with displaying the sentence array outside of for loop
int example(string sentence)
{
int i = 0;
for (i; 1 < 50; i++)
{
cout<<sentence[i]<<endl;
}
cout<<sentence[i]<<endl;
return 0;
}
outside of for loop, sentence[i] isn't showing the character at sentence[49]
can someone tell me the reason?
Try this
int example(string sentence)
{
int i = 0;
for ( ; i < 50; i++)
{
cout<<sentence[i]<<endl;
}
cout<<sentence[i]<<endl;
}
You want to check if i is less than 50, not if 1 is less than 50, because that would always be true and the loop never terminates. Also, in the snippet I posted, i will have the value of 50 after the loop, so there better be a 51st element (0-based array).
The reason that it isn't displaying sentence[49] is that i is 50 after the loop runs. The i++ in your loop increments i after the loop iteration has run. So when i is 49 it will run through the loop and and then increment i to 50. Then it comes around to the conditional i < 50 and it sees that i is now 50 and the loop terminates. Then when you call sentence[i] outside of the loop it is trying to display sentence[50]. To get at the last character in sentence I would suggest one of the following:
cout << sentence[i - 1] << endl;
or the much easier to read:
cout << sentence.back() << endl;

Searching by price in a 2D array?

I have a program that builds a 2D array of a theater. The user can select a seat by position and the monetary amount is changed to a 0 to indicate that the seat is taken. The other method of choosing a seat selects by price. So the user enters a price, a for loop iterates through the array and finds the first instance of that price and replaces it with a 0, then stops. Or at least that's what I tried to do. In practice, it replaced all of those values with 0. I tried using a while loop to close it out once the condition is met, but that didn't work. Here's my (relevant) code.
while (flag == true)
{
cout << "\n";
cout << "You may select tickets by seat or by price. Enter 1 to select by price, or 2 to select a seat. Enter 3 if you'd like to quit." << endl;
cin >> userSelection;
if (userSelection == 1)
{
cout << "What price would you like to search for? " << endl;
cin >> priceSelection;
while (searchFlag == true)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
if (Theater [i][j] == priceSelection)
{
Theater [i][j] = 0;
searchFlag = false;
}
}
}
for (int i = 0; i < 9; i++) // This for loop is going to output our array so the user can see pricing.
{
for (int j = 0; j < 10; j++)
{
cout << Theater [i][j] << " ";
}
cout << "\n";
}
}
}
I'm not sure what really needs to change so that it'll stop after the first price is found and changed. Also, I don't mind to copy/paste the rest of my code if that's necessary.
Just some advice for the future,
Don't hardcode your loop termination conditions i.e. (i < 9). Have a current length of the array, or number of seats. That way you ever add more, this will still work.
Also even though you set search flag to false in your if statement, you will still continue through every for loop. So you will iterate through every seat, every time. If the price at the of the current seat never matches the user inputted price, you will go into an infinite loop. Try changing your inner for loop to
for (int j = 0; j < someCurrentLengthOfArray && searchFlag; j++)
That way you will check if the price matches and if you head an unspecified end of the array.
As was mentioned in one of the comments, why is this a 2D array?
Your while loop is outside the for loop, so all the replaces finish before you get back to the while loop. If you use #Dieter Lücking suggestion and just use a 1D array you can do this with one while loop
int i =0;
while (searchFlag == true)
{
// ..check for seats
if (seatFound)
{
searchFlag = false;
}
i++;
}
For 2D arrays you can still use the while loop method, it will just take two of them.
change your for loops:
for (int i = 0; i < 9 && searchFlag; i++)
{
for (int j = 0; j < 10 && searchFlag; j++)
{
if (Theater [i][j] == priceSelection)
{
Theater [i][j] = 0;
searchFlag = false;
}
}
}
The way they are now, they'll keep iterating through, until the end, no matter what. If you do as I showed above, they will break when searchFlag is set to true, and pull back out into the outer while loop, which will also then break.

Loop not giving expected answer - unsure about exit/return/break

I am testing a simple piece of code in order to learn about using queues (as well as practizing vectors).
I have written this piece of code:
#include "stdafx.h"
#include <iostream>
#include <queue>
struct msgInfo //contains the attributes as gleaned from the original (IP) message
{
int age;
std::string name;
};
using namespace std;
int main ()
{
vector<vector<queue<msgInfo>>> nodeInc; //container for messages
int qosLevels = 7; //priority levels
int nodes = 5; //number of nodes
vector<queue<msgInfo>> queuesOfNodes(qosLevels);
int i;
for (i=0; i<nodes; i++)
{
nodeInc.push_back(queuesOfNodes);
}
msgInfo potato, tomato, domato, bomato;
potato.age = 2;
potato.name = "dud";
tomato.age = 3;
tomato.name = "bud";
domato.age = 4;
domato.name = "mud";
bomato.age = 5;
bomato.name = "pud";
nodeInc[2][2].push(potato);
nodeInc[2][2].push(tomato);
nodeInc[2][3].push(domato);
nodeInc[2][3].push(bomato);
for (int j = 0; j < 2; j++) //simple loop for testing: for each round, output the age of only one 'msgInfo'
{
cout << j << endl;
for (int k = (qosLevels-1); k >= 0; k--)
{
if (!nodeInc[2][k].empty())
{
cout << nodeInc[2][k].front().age << endl;
nodeInc[2][k].pop();
return 0;
}
else
break;
}
}
}
The output I get is
0
1
but what I am trying to get is
0
4
1
5
What am I doing wrong here? I can't figure out where my logic is wrong - it seems to me that here it should output the first two elements belonging to the highest filled priority level. I think it has to do with how I am exiting the loop - essentially I want each round of the for loop to only output the age of one msgInfo before 'pop'-ing it - but I have tried exit/return/break and it hasn't worked.
edit
I am receiving messages from nodes. These messages need to be put into a queue according to their attributes: node and priority level. I have decided to use a vector<vector<queue<msgInfo>>> to do this -> essentially node < priority level < queue for messages > >. When accessing this container, I need it to output the age of one msgInfo at a time - the msgInfo will be the front of the queue of the highest priority level. Not all priority levels will be filled, so it needs to iterate from highest priority level to lowest in order to find the relevant element.
I need to design a loop that will output these one at a time (because other processing needs to be done between each round of the loop).
The closest I can get to is this:
for (int j = 0; j < 2; j++) //simple loop for testing: for each round, output the age of only one 'msgInfo'
{
cout << j << endl;
for (i = (qosLevels-1); i >= 0; i--)
{
if (!nodeInc[2][i].empty())
{
cout << nodeInc[2][i].front().age << endl;
nodeInc[2][i].pop();
//return 0; <--------DON'T return. this terminates the program
break;
}
//else
// break;
}
}
That returns:
0
4
1
5
As is stated in the comment, invoking return 0; returns from main() and therefore terminates the program ( actually kind of a peaceful exit ).
What do you expect return 0 and break to do?
return 0 exits the entire main function, so your program would end once it encounters a non-empty queue.
break terminates the innermost enclosing loop (which is for (i ...)). In other words, your current logic is:
For each j of 0, 1 do:
If nodeInc[2][qosLevels - 1] is not empty, print its front and exit program; otherwise try no more is and do next j.
I don't know what the intended behaviour is, but based on the "expected output" you gave, you should replace return 0 with break, and omit the else clause entirely.