Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make a for loop that adapts to vector size?

Im currently making a program that will return the values of 3x+1 given starting value x.

Here is the trimmed code.

                        //3x+1
                        //starting at any positive integer (x)
                        //multiply by 3 then add one
                        //(n%2==0?/2:3n+1)

                        std::vector<int> Holder;
                        int usrNum;
                        std::cin >> usrNum;
                        
                        Holder.push_back(usrNum);
                        Holder.push_back(3*usrNum+1);

                        for(int i = 1; i < 200; i++){
                            (Holder[i]%2==0?Holder.push_back(Holder[i]/2):Holder.push_back(3*Holder[i]+1));
                        }
                        
                        for (int i = 0; i < Holder.size(); i++) {
                            std::cout << Holder[i] << " ";
                        }
                        

currently im using 200 as a hard coded value because if i use i < Holder.size() it causes an infinite loop and i never catches up.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

anyone have any ideas as to how i can make it loop until it reaches the value 1?

>Solution :

Use a while loop, with the termination condition being when the last element is 1. Have a look at this reference for std::vector for help.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading