Infinite "true" while loop - c++

I know I am probably just doing something dumb wrong, but I need to take a number from the user, create an infinite loop (by making my while statement true) of multiples of 2. I got the math to multiply the number from the user times itself, but I can't get it to loop. This is the last part of my homework for the week and my brain is fried, so I can't figure out where I went wrong!
Any help would be amazing! Here is what I have:
#include <iostream>
using namespace std;
int main (int argc, const char * argv[])
{
int d;
int e;
cin >> d;
while (true)
{
e = d * d;
}
cout << e << ", ";
}

There is unreachable code at: cout << e << ", ";
Perhaps this was meant to go in the while loop?
You are assigning e the value of d*d over and over. Because d*d does not change, the value of e never changes. Perhaps you should initialize e to the number you want outside of the loop, and then set e = e * 2 inside of the loop, then print e. This will print multiples of your number by successive powers of 2, which is what I think you want.

As written, your code will loop forever and, as a result, it will never get to that cout statement. Maybe you want to put the cout statement inside of the loop body so that the variable gets printed?

One of the the possible solutions:
int main (int argc, const char * argv[])
{
int d;
int e = 2;
cin >> d;
while (d>0)
{
cout << e << ", ";
e = e * 2;
d--;
}
}

Related

User inputs N, find all pairs of a and b co-primes where a<N & b<N

#include <iostream>
using namespace std;
void gcd(){
int a,b,hcf;
for (int i = 1; i <= b; ++i) {
if (a % i == 0 && b % i ==0) {
hcf = i;
}
}
}
void pirm(){
int a,b,n,hcf;
for (int a=1;a<n;a++){
for (int b=1;b<n;b++){
gcd();
if (hcf==1) {
cout << a << " and " << b << endl;
}
}
}
}
int main(){
int n,a,b,i,hcf;
cout << "Enter a natural n, less than 100" << endl;
cin >> n;
if (n>=1 && n<100){
pirm();
}
else
cout << "You didn't enter a natural number" <<endl;
}
When I run it and enter a number, it doesn't do anything. The task is as follows:
User enters a natural N, that is less than 100. Find and output all pairs of co-primes that are < 100.
As you can tell by the code, I'm a complete newb at C++. Just wondering why the program "stops" or where I messed up the code in general. Any help is greatly appreciated.
There are a number of issues here.
First, the direct answer to your question: your program never prints because it never executes a print statement. If you enter a natural number, but hcf is never equal to 1, you will never print anything.
Now the question becomes why is hcf never 1? And that's where we start to run into more issues with your code. The main misunderstanding seems to be about scope. If you declare variables inside a function, they are within the function's "scope" -- the function can use them, and any scope inside the function can use them (e.g. loops and conditionals), but no outer scope can use them. You declare a, b, and hcfseveral times, but you only ever use them in gcd(). Not only is this unnecessary, but critically, these are different variables. You change the hcf in the scope of gcd(), but the hcf in pirm() is unchanged!
There are many ways to do what you're trying to do. The one that's closest to what you already have is to have gcd() take parameters by reference. If you change your declaration of gcd() to void gcd(int a, int b, int &hcf), and do not redeclare those variables in the first line of the function, then you are able to modify hcf in a way that will stick even when the function goes out of scope. You will then need to change your call on line 15 to gcd(a,b,hcf);.
Your algorithm could also be improved, though I believe it will still work. If you're interested in a more canonical way to find the gcd, try looking into Euclid's algorithm.
You should learn how to pass arguments to a function. Corrected your code for you, seems to be working:
#include <iostream>
void gcd(int &hcf, int a, int b)
{
for (int i = 1; i <= b; ++i)
{
if (a % i == 0 && b % i == 0)
{
hcf = i;
}
}
}
void pirm(int n)
{
int hcf;
for (int a = 1; a<n; a++)
{
for (int b = 1; b<n; b++)
{
gcd(hcf, a, b);
if (hcf == 1)
{
std::cout << a << " and " << b << std::endl;
}
}
}
}
int main()
{
int n;
std::cout << "Enter a natural n, less than 100" << std::endl;
std::cin >> n;
if (n >= 1 && n<100)
{
pirm(n);
}
else
std::cout << "You didn't enter a natural number" << std::endl;
system("pause");
return 0;
}

How do i set a variable again in a loop

I'm new to c++ and have a question with variables
int main() {
int a;
int b;
int c;
int e;
int parafechar;
int loop = 10;
while(loop==10) {
cout<< "Coloque a mensal 1\n";
cin >> a;
cout<< "Coloque a mensal 2\n";
cin >> e;
cout <<"Coloque a nota do cnem\n";
cin >> b;
cout << "Coloque a media dos trabalhos\n";
cin >> c;
if(a>b) {
cout << "A media e : " << a*0.5 + b*0.25 + c*0.25<<endl;
} else {
cout << "A media e : " << e*0.5 + b*0.25 + c*0.25<<endl;
}
cout << "aperte uma tecla para fechar o programa\n";
cin >> parafechar;
}
return 0;
}
after the last line i want the code to run again and all the variables to be set again but the program goes on endless, what should i do ?
( the program is in portuguese but it calculate grades)
thank you for your time and help :)
after the last line i want the code to run again and all the variables to be set again but the program goes on endless, what should i do?
Change the check in while and change the value of loop so that it will eventually meet the condition to stop the loop.
while(loop > 0) {
// Do your stuff...
// Decrement loop. It will eventually become zero
// and the conditional in the while statement will fail.
--loop;
}
The line
while (loop==10)
will give always true because the value of loop is not changing trough out the program.
What i can understand is , You want to iterate your loop 10 Times. So in this case you should write :
while (loop>0){
// your code of calculating grades
loop--;
}
Since you want the loop to be executed 10 times , you can do:
int loop = 10;
while (loop--) {
//do something
}

Is there a way in C++ to only return the the last instance of a for loop?

Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}

Trying to make a while Loop that subtracts a number until it reaches desired value and if subtraction surpasses desired value, display it and stop

I'm new to programming and to c++ so I know this is probably a silly question but I would really appreciate the help. just as the tittle says, I'm trying to make a subtraction while type loop that reaches a desired value, in this case: 0
The code uses two random numbers from the user input. The first number is the minuend, the second is the subtrahend
However, the problem that I'm having is that if subtraction surpasses desired value, the loop will not display it and the user will see displayed a number higher value than 0. I want to fix so it displays the negative number closest to 0 and then stop. Here's the code:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
cout <<" enter a: ";
cin >> a;
cout << "enter b: ";
cin >> b;
while ( a > 0 )
{
cout << a << '\n';
a= a-b;
}
return 0;
}
What am I doing wrong, how can I fix it? Thanks
You're printing a before decreasing it. Try switching the statements inside your loop like so:
while ( a > 0 )
{
a = a - b;
cout << a << '\n';
}
You could just add
cout << a << '\n';
again after your loop - you know you have the right value then. Or you could possibly avoid duplicating that line by switching to using a do ... while loop.
Hi i just switched this code:
while ( a > 0 )
{
cout << a << '\n';
a= a-b;
}
to this and it worked as you explained:
while ( a > 0 )
{
a= a-b;
cout << a << '\n';
}

multiplication game loop slide issue

So I am determined to make an epic math console based game for fun.
I am curious as to why when the random enters a zero, the program slides through a series of multiplied by 0 and skips the "please enter: " portion of my code.. Is this because of the true and false boolean features of the test condition in the while loop? More importantly how can I stop this from happening?
Thank you for all of your help!
// multiplicationgame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void game();
int _tmain(int argc, _TCHAR* argv[])
{
// waiting.cpp : Defines the entry point for the console application.
//
cout << "Welcome to Math game!\n\n" << endl;
float secs;
secs = 3;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start < delay )
;
char choice = 'z';
game();
while(choice != 'n')
{
cin >> choice;
if (choice == 'y')
{
cout << "\n\n";
game();
}
else
choice = 'n';
}
return 0;
}
void game()
{
float secs;
secs = 33;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
int correct = 0;
while (clock() - start < delay )
{
srand(time(NULL));
int a = rand() % 23;
int b = rand() % 23;
int c = (a * b);
int d = 0;
char choice = 0;
cout <<"What does " << a << " * " << b << " equal?" << endl << endl << endl;
cout << "\n";
while(d != c)
{
cout << "Please enter a number: ";
cin >> d;
if(d == c)
++correct;
}
cout << "\n\nCorrect! " << (a * b) << " is the answer!" << endl << endl;
}
cout << "Your score is: " << correct << "\n\n" <<endl;
cout << "Would you like to play again (Y) or (N)?\n\n\n";
}
You assume the answer is wrong if c is not equal to d, but if a or b are set to zero , c and d are equal before your user can ever enter a number. One solution would be to use a do { ... } while ( ... ); loop instead of a while loop to ensure the user is always asked for a number before your test for the correct answer is performed.
As Markku said, don't set d = 0, because if either a or b is equal 0, then c = a * b = 0 and then your while loop condition c != d won't hold and so it will be skipped
You initialize d to be 0, and anything times 0 is 0. Thus the (d != c) condition will always be false, and you don't enter the while(d!=c) loop.
You are getting 0 several times, because the while loop finishes very quickly, and so when you call srand(time(NULL)), time(NULL) will return the same value as the previous itteration, and you get the same random seed (which gets you 0 again).
initialize d to be -1 (or some other value that a*b can't be). Move the srand outside of your while loop -- you only have to (and only should) call srand once in your program.
John
Quick fix: initialize int d = -1; instead of int d = 0;.
You're initializing int c = a * b. Since either a or b is zero, the multiplication results in c being zero. You also initialize int d = 0;. Then you have while(d != c), but you assigned both of them to zero, hence your program skips over that loop because d != c is false.
#AEGIS No, the srand(time(NULL)) merely seeds the random number generator with a somewhat random value based on the current time whenever the program is run. This ensures that each run of the program will produce a different set of multiplication problems to solve.
#AEGIS The outer while (clock() - start < delay ) { ... } loop terminates when the "delay" time has expired. The inner while(d != c) { ... } loop is never entered at all when a or b are zero, or loops forever as long as the user enters wrong answers. So though it is not a real problem in practice -- any user is likely to finally get the correct answer or abort the program manually -- this is a program which is not certain to ever terminate.
#Ned Nowonty looking at the screen shot AEGIS provided the outer loop didn't terminate. If it did then the
Your score is: (some number)
Would you like to play again (Y) or (N)?
would have appeared. When you srand with the same initializer you end up with the same pseudo random numbers. So when one of the variables was initialized to 0 it would loop around until time(NULL) provided srand a different variable. In order to avoid that you could use an iterator as well as the time function so the seed would be different all the time.