Nested loops C++ - c++

So I am making a program that will create a square based on the users desired size. My code so far reads the value, prints out the top of the square but i'm getting caught up on how to set up the sides because of a nested loop I've created. The issue here is that I need for the loop to reset it's values every time it exists.
Here's my code so far:
#include <iostream>
using namespace std;
int main(int,char**) {
int x;
int z=1;
int l=0;
int n=0;
int q=1;
int m=0;
int o=0;
do{
cout << "Enter length between 0 and 64 (-1 to exit): ";
cin >> x;
if (x>-1&&x<64){
cout << "+";
for (;x-2!=n;++n){
cout << "-";
}
cout << "+" << endl;
}
else{
cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit.";
}
do {
cout << "|";
do {
//cout << " ";
//++m;
//}while (x-2!=m);
cout << "|" << endl;
++o;
}
while (x-2!=o);
++z;
}
while (z!=5);
}
The commented out portion is where the program is getting caught up at, it seems that when I increment m until it exits the do while loop, it holds onto the value that it was incremented to. I know that a continue statement breaks from the loop and begins a new iteration of the loop but it doesn't seem to want to fit inside the do-while loop even if i create an if statement such as
if (x-2==m){
continue;
}
Any help would be appreciated

Just put m = 0; before the loop.
m = 0;
do {
cout << ' ';
++m;
} while (x-2 != m);
Or use a for loop instead;
for (int m = 0; m != x-2; m++) {
cout << ' ';
}
This is the more common idiom for repeating something a certain number of times, since you can see all the conditions related to the loop in a single place.

Related

Why is one of the while loops not being executed (C++)?

I am using the book "Programming : Principles and Practice Using C++(Second Edition)" by "Bjarne Stroustrup". I am stuck in the last exercise question of the chapter 4. I have tried to look up the solutions for this particular question but I am not getting the solution for the Second Edition.
There are two extensions for this question and each one requires a while-loop. Only the first while-loop is getting executed and it doesn't matter which one I place first.
The question is "Write a program where you first enter a set of name-value pairs. Terminate input with NoName 0. Each and every name entered must be unique."
Extension for the question is "Modify the program so that when you enter the name, corresponding score will be the output."
Extension for the question is "Further modify the program so that when you enter the score, corresponding names will be the output."
int main()
{
cout << "Enter a name and score side-by-side and enter 'NoName 0' when done :\n";
int scores_temp{ 0 };
string names_temp{ 0 };
vector <int> scores;
vector <string> names;
int adder{ 0 };
while (cin >> names_temp >> scores_temp)
{
if (names_temp == "NoName")
{
if (scores_temp == 0)
{
break;
}
}
else
{
for (int i = 0; i < names.size(); i++)
{
if (names_temp == names[i])
{
adder++;
}
}
if (adder == 0)
{
names.push_back(names_temp);
scores.push_back(scores_temp);
}
else
{
cout << "\nYou can't enter the same name twice.\n\n";
break;
}
}
}
for (int j = 0; j < names.size(); j++)
{
cout << names[j] << "\t" << scores[j] << "\n";
}
cout << "Enter the name to get the corresponding score and enter Ctrl+Z when done : \n";
string name_score{ 0 };
int counter{ 0 };
while (cin >> name_score)
{
for (int l = 0; l < names.size(); l++)
{
if (name_score == names[l])
{
cout << "Score of " << names[l] << " is " << scores[l] << ".\n";
}
else
{
counter++;
}
}
if (counter == names.size())
{
cout << "Name not found.\n";
}
counter = 0;
}
cout << "Enter the score to get the corresponding names and enter a character when done : \n";
int score_name{ 0 };
int incrementer{ 0 };
while (cin >> score_name)
{
for (int k = 0; k < scores.size(); k++)
{
if (score_name == scores[k])
{
cout << "Score of " << scores[k] << " was obtained by " << names[k] << ".\n";
}
else
{
incrementer++;
}
}
if (incrementer == scores.size())
{
cout << "Score not found.\n";
}
incrementer = 0;
}
keep_window_open();
return 0;
}
The header file for the program is given by Bjarne himself. The website for the header file is :
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
There are two extensions for this question and each one requires a while-loop. Only the first while-loop is getting executed and it doesn't matter which one I place first.
while (cin >> name_score)
This first loop continues until cin fails. If cin has already failed, it won't even loop once.
while (cin >> score_name)
Since we only get to this second loop if cin has failed, and this loop won't even loop once if cin fails, the code inside this while loop can never execute.
You either need some way to exit that first while loop without input having to fail, like the NoName 0 does in the very first loop or you need to clear cin's fail flag between these while loops.
See Why would we call cin.clear and cin.ignore() after reading input? for more details.

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;
}

I'm trying to write a program which outputs "n" (input) fibonacci numbers

I am struggling with my program. It should output n Fibonacci numbers, each on a new line. If the Fibonacci number exceeds the range of an unsigned int you should just exit the program. Moreover, you should print on a new line how many Fibonaccis of "n" are displayed.
Here is the code so far:
#include<iostream>
#include<limits>
using namespace std;
int main()
{
unsigned int n;
cout << "Please enter the amount of fibonaccis you would like to compute: " << endl;
cin >> n;
unsigned int next=1;
unsigned int current=0;
unsigned int c = current;
unsigned int temp;
unsigned int counter=1;
//This bool returns true as soon as an overflow occurs
bool overflow;
/*This bool checks, whether the newly computed
number is bigger than the previous number
(which may not be the case if an overflow occurs)*/
bool nextBigger;
/*Somehow, I could only handle the first
inputs by using "bruteforce".
If I tried to combine it with the "main loop",
it got all messy. */
if(n==0)
{
std::cout << "0" << " of " << n << endl;
}
else if(n==1)
{
std::cout << "0" << endl << "1 of " << n << endl;
}
else if(n==2)
{
std::cout << "0" << endl << "1" << endl << "2 of " << n << endl;
}
else
{ /* This for-loop increases (at least it should) a counter
by one for each computation of a valid fibonacci number*/
for(counter=1;counter<n;++counter)
{
overflow = (c > (std::numeric_limits<unsigned int>::max()-temp));
if(!overflow && nextBigger)
{
cout << next << endl;
}
else
{
break; //If overflow or next number < previous number, exit program
}
temp = next; //temp is storage variable for next
c = current; //storage variable for current
next += current; //next is being altered: it becomes the new fibonacci number
current = temp; //current gets value of temp( value of next before being altered)
}
nextBigger = (next > current);
cout << counter << " of " << n << endl; //Output of how many fibonaccis were computed
}
return 0;
}
So here is the thing. I programmed it in CodeBlocks, where it worked perfectly. But then I tried to upload it in Codeboard (as an assignment). In Codeboard it suddenly didn't work at all. Maybe it has to do with the different compilers, but I really have no clue how I could fix this issue. So I am quite puzzled and I'd be very thankful for any hints, ideas, corrections or inspirations.
(I am a beginner, so I hope the code is understandable and readable. I am open for suggested improvements.)
Looking at your code it seems the body of the if statement
if(!overflow && nextBigger)
{
cout << next << endl;
}
is never executed. Maybe print the values for overflow and nextBigger on each loop iteration so you can debug what's happening.

C++ , 1 cin enter everything for array

this is my code about bubble sort.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int &a, int &b) {
int * x = &a;
int * y = &b;
int tmp = * x;
* x = * y;
* y = tmp;
}
int main()
{
// INPUT
int size;
int i=0;
int A[80];
cout << "How many number in your list A ? ";
cin >> size;
for(i=0;i<size;i++) {
cout << " A[" << i << "] = " ;
cin >> A[i];
}
// PRINT LIST
cout << "This is your list number: ";
cout << endl;
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
// WHILE LOOP , continue if swapped;
bool swapped = true;
int pass=0;
while(swapped == true) {
swapped = false;
// Increase Pass
pass++;
cout << endl << endl << "Pass " << pass << ":";
// Loop size - Pass;
for( i=1; i<=size - pass;i++) {
// check if X > Y
if(A[i-1] > A[i]) {
// true, doing swap
swap(A[i-1], A[i]);
// set swapped to continue next loop
swapped = true;
}
// Print list again after sort;
cout << endl;
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
}
}
// PRINT after sort;
cout << endl << endl << "Your list after sort: ";
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
On this code,i must enter number of amount (size), and then enter each of A[i].
But I want to improve this code, can i don't need to enter amount (size), and just cin the the whole A?
Like:
Please enter your list number: 5 1 4 2 8 [enter]
And I get the whole A[];
Just a idea after see first answer. I see, Vector can automatic resize, but if I change into vector, will have any way to enter 1 line ? I just got an idea, I enter a string of number: 1 2 3 4 5, then I enter. do C++ have any function to split by space, and then return back to an array or a vector ? in PHP, I just use $array = explode(" ",$string); >_<
Thanks your help, tried to read many article >_<
What you should use instead of an array, is a vector. Arrays require you to know in advance how many elements will be stored, and if this number is unknown, you have to employ some rather involved memory copying once you need to exceed their predetermined capacity. Vectors do this for you under the hood.
Here's an example that basically performs what you ask, using a vector:
std::vector<int> intList;
std::string inputStr;
std::cin >> inputStr;
std::string subStr;
for ( std::string::iterator _it = inputStr.begin(); _it != inputStr.end(); ++_it )
{
if ( *_it == ',' )
{
intList.push_back( atoi( subStr.c_str() ) );
subStr.clear();
}
else
subStr.push_back( *_it );
}
if ( subStr.size() > 0 )
intList.push_back( atoi( subStr.c_str() ) );
Now intList is populated with the integers you have entered, so long as each is separated by a comma.
The easiest way to do what you want to do is to have some sort of termination marker that it is the end of the array. For example, you could use the word "done" or the number -999 to indicate the end. Then instead of a for loop to read in, you would have a do...while loop like
do
{
std::string foo;
cin >> foo;
...
} while (foo != "done");
Note that you are probably going to want to change the A[] variable from a regular array to a std::vector. Then it will store it will expand automatically and store its own size for your output. Otherwise you would have to keep another variable to store how many elements were put in(and your user could not enter more than 80 elements).