Utilizing the While Loop - c++

The prompt is to start with a random number and to keep replacing that number repeatedly under the conditions that (1) if the number is even, you divide it by two and (2) if the number is odd, you multiply it by three then add one.
So, for example:
If the number was 13, then the output would be: 40 20 10 5 16 8 4 2 1
(Also the program must stop after the value of 1 is reached)
#include <iostream>
using namespace std;
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
while(x%2==1)
{
x=x*3+1;
cout << x << " ";
lengthcount++;
}
if(x==1)
{
return 1;
}
cout << "Length:" << lengthcount << endl;
}
This is what I have so far. But when I compile and run the code only the first value of 40 appears. Not the rest of components. I'm assuming it has to do with the loops not connecting with one another. How do I get it so that the output of one loop would go to the other loop and back?

Two sequential loops aren't connected, and there's no way that you can or should make them so.
Instead, have a single loop, with an if/else inside it to handle the odd/even cases respectively.

The way the code currently is, neither the division by 2^n, nor the 3n+1 operation can be performed more than once. You need to have an outer loop around these operations.
The correct way to exit a loop is with the break keyword, not return.
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
while(true) {
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
if(x==1)
{
break;
}
x=x*3+1;
cout << x << " ";
lengthcount++;
}
cout << "Length:" << lengthcount << endl;
}

How do I get it so that the output of one loop would go to the other loop and back?
You syould introduce loop in your code.
Furthermore, because 1%2==1 is true, x==1 should always be false after while(x%2==1).
An example of fixed code:
#include <iostream>
using namespace std;
int main()
{
int x;
int lengthcount=0;
cout << "Enter a number: ";
cin >> x;
for(;;)
{
while(x%2==0)
{
x=x/2;
cout << x << " ";
lengthcount++;
}
if(x==1) // check if the value of 1 is reached
{
break;
}
while(x%2==1)
{
x=x*3+1;
cout << x << " ";
lengthcount++;
}
}
if(x!=1) // x should be 1 in here
{
return 1;
}
cout << "Length:" << lengthcount << endl;
}

Related

How to loop the program's asking for new set of inputs in c++?

Consider the following code:
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}
How can I make the program endlessly repeat asking for a new set of numbers as input?
Here's the simplest way of doing what you want (there are other ways). Basically, you just need to 'wrap' the code that you want to repeat in a loop, where the 'test' condition for the loop will always evaluate to true.
Note the comments with "///" I've given:
#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;
int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}
Feel free to ask for further clarification and/or explanation.
Depends on what exactly do you want your program to do. If you want it to "deny access". For example lets say you have want a number K > 3 always for the program to continue. The all you have to do is use a do- while loop:
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
Otherwise just use a normal loop with the condition suitable for the task.
Suppose your program is to find the Factorial of number and you want it to loop such that it ask for new value from the user
int main()
{
int n;
while (true) {
int factorial = 1;
cin >> n;
if (n==0) {
cout << 0;
}
else {
for (int i=n;i>0;i--) {
factorial = factorial*i;
}
cout << factorial;
}
}
return 0;
}

adding digits in an array c++

I'm new to C++ and i was trying to understand how to work with arrays. The idea I have is:
I wanted a user to input an array, the program to output the
array
Double all the values in the array and output that
And for each of the doubled values, add the digits of the doubled number
(1 digit number would remain the same), then output the new numbers as
well.
(e.g. if the array was [5, 6, 7, 8], the doubled values would be [10, 12, 14, 16] and then you would add each values digits like, [1+0, 1+2, 1+4, 1+6] to get [1, 3, 5, 7].
I put my code to show my progress, feel free to point out any errors along the way!
Any help is appreciated!
p.s. The nested loop didn't work :(
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i];
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j];
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
for (int k=0;k<maxNum;k++)
{
for (int l=0;l<maxNum;l++)
{
int sum[20];
while (num[k]!=0)
{
sum[l]=sum[l]+num[k]%10;
num[k]=num[k]/10;
}
}
cout << sum[l];
}
cout << endl;
}
A few things:
maxNum and num[] are never initialized, it's dangerous.
that is not how you scan input. Ideally you woud do smth like while(cin >> tem_var){}. Or you could modify it to be if( !(cin >> num[i]) ) break;. That way you don't need to do maxNum-1 later too. (cin>>) will be True if it reads a variable succesfully and False otherwise. That way you can stop scanning by entering any non-number string, instead of running the loop for the rest of iterations, but leaving num[i] uninitialized if that happens.
you forget to output delimeters between array numbers which makes it hard to read.
cout << num[i] << "|"; or smth.
In the last part you make 3 loops: a k for loop that you never use, a l for loop to iterate num, and a k while loop to sum the digits. One of them is not necessary.
In the last part sum[] array, though filled correctly, is not outputted. You declare it inside the l loop, meaning it's deleted when you exit it. And even if you declared it outside. your cout << sum[l]; is outside the l loop, meaning it will only try to do the cout << sum[maxNum]; (the value of l the loop finishes with) while you only have [0:(maxNum-1)] elements in num and sum filled.
I'd suggest you try smth like for(k=1;k<num[l];k*=10) sum[l]+= num[l] / k % 10; instead of that while loop. It's shorter, gets the job done and leaves num[l] unchaged in case you decide to use it again afterwards.
You need to initialize sum array with all zeros first. You don't need nested loop.
Create a sum array to store the sum of each number and initialize it with 0's. First write a loop to traverse through the elements of the doubled array. For each element write a loop(you chose while loop) to traverse through the digits of each number and them to the corresponding sum element.
I've modified your code a little bit, go through it once.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i]<<' ';
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j]<<' ';
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int sum[20];
for (int i=0;i<maxNum-1;i++)
sum[i]=0;
for (int k=0;k<maxNum-1;k++)
{
// for (int l=0;l<maxNum;l++)
// {
while (num[k]!=0)
{
sum[k]=sum[k]+num[k]%10;
num[k]=num[k]/10;
}
cout << sum[k]<<' ';
// }
}
cout << endl;
}
You don't need nested loop for that ,while making logic behind any program take a simple example and get the result,Don't jump directly to code. This will help you to building logics.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
int sum=0;
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum;i++)
cout << num[i]<<ends;
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum;j++)
{
num[j]*=2;
cout << num[j]<<ends;
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int r=0;
for (int k=0;k<maxNum;k++)
{
while (num[k]>0)
{
r=num[k]%10;
sum+=r;
num[k]=num[k]/10;
}
cout<<sum<<ends;
sum=0;
r=0;
}
cout << endl;
}

Program loops forever when entering 10 digits on CIN

Can you help me guys? I'm a total beginner. My code worked fine then KEEP LOOPING FOREVER and never goes back to or cmd would crash with "Process terminated with status -1073741676". It should loop once then CIN >> again. It happens when I enter 10 digit numbers in my CIN >>.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class noteAssign { //This class return "A" if the random number generated is between 1 and 10
public:
int x;
int noteOut(int x){
if(x>1 && x<10){
cout << "ITS A" << endl;
return x;
}else{
cout << "IT'S NOT A" << endl;
return x;
}
}
}gonote;
int main()
{
cout << "Match the note's Hertz!" << endl;
cout << "Your answer may range from 1 to 20" << endl;
cout << "Type 0 to quit" << endl;
int noteIn; //No real purpose YET
do {
srand(time(0)); //ADDING MULTIPLE RAMDOMIZER FOR WIDER RANDOM RANGE
int rand1 = 1+(rand()%20); //randomizer 1
int rand2 = 1*(rand()%20); //randomizer 2
int hzout = (rand1 * rand2 + rand1 / rand2)%20; //rand 3
noteAssign gonote;
cout << gonote.noteOut(hzout) << endl; //calls the function and gives the parameter
cin >> noteIn; //No real purpose YET
} while(noteIn != 0); //program quits when you enter "0"
};

looping back to start of do while loop [C++]

I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.
Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed
You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.
It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}
A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}

How do I loop a variable?

I have made a "program" that just says welcome! Type two numbers you want to be added to each other:
there you type the two numbers and then you get the answer out...
When that is done it says: Press any key to continue . . .
When you press a key the program shuts down, but I want it to restart when you pres any key...
How do I do that? I use Microsoft visual studio express 2013 for windows desktop...
langue is C++
This is my code:
#include <iostream>
#include <limits>
#include <cstdio>
using namespace std;
int Add(int x, int y)
{
cout << "Calculating the sum of " << x << " + " << y << "\n";
return (x + y);
}
int main()
{
cout << " Welcome!\n";
int a, b, c;
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nShutting down....\n\n";
system("pause");
return 0;
}
To loop, you can use while.
For example:
while (false) {
std::cout << "You will never see this output" << std::endl;
}
bool loop = true;
while (loop) {
std::cout << "Type 'quit' to quit this loop." << std::endl;
std::string input;
// This will grab a *single word* from the input. If you want a line, look
// at std::getline
std::cin >> input;
if (input == "quit") {
loop = false;
}
}
while (true) {
std::cout << "This will be repeated forever" << std::endl;
}
There are also two other forms, do while:
std::string input;
do {
std::cout << "Type 'quit' to quit." << std::endl;
std::cin >> input;
} while (input != "quit");
... and for (which is generally used for loop over a defined list of things):
for (size_t i = 0; i < 10; ++i) {
std::cout << i << " out of 10" << std::endl;
}
Technically you can use any of these loop types for any kind of looping, but I suspect the type you want is either one of the two standard infinite loops (whichever one you prefer):
while (true) {
// stuff to repeat forever
}
for (;;) {
// stuff to repeat forever
}
... or a do while loop similar to the do { ... } while (input != "quit"); loop above.
int main()
{
cout << " Welcome!\n";
int a, b, c;
while (true)
{
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress a key to go again....\n\n";
system("pause");
};
return 0;
}
You can do something like this:
int main()
{
cout << " Welcome!\n";
int a, b, c;
while(true) {
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress any key to continue\n";
system("pause");
}
return 0;
}
Use a do while loop mentioning your condition
before exiting the program so that you can determine when to continue and when to exit
I am not sure I understand your question, but I think this is what you are looking for. Have a boolean that determines if the program will loop or not.
int main() {
// stillRun is true while we want to keep looping the program
boolean stillRun = true;
while(stillRun) {
runProgram() ; // this function has all the other code in your old main() function
cin >> stillRun ;
}
}