Simple Nested Loop Issue. * Shape * - c++

I am having a brain shock right now so I wanted to ask very simple question.
Currenly, I am trying to print out starts like this
when input is 7 , the output is
*
**
*
**
*
**
*
and here my code is , it prints 14 times instead of 7 or when I put N/2 it doesnt print the odd number.
#include <iostream>
using namespace std;
int main () {
int N;
cout << " Please enter N " ;
cin >> N;
for (int i = 0; i < N ; i++) {
cout << "*" << endl;
for (int j = 0; j < 2; j++) {
cout << "*" ;
}
cout << endl;
}
}

For each N you are printing two lines, with single * and another with two *. Instead just print single line with either one or two star based on the line is odd or even.
#include <iostream>
int main ()
{
unsigned int N;
cout << " Please enter N " ;
cin >> N;
for(unsigned int i = 0; i < N; ++i)
{
if(i%2 == 0)
{
std::cout << "*" << std::endl;
}
else
{
std::cout << "**" << std::endl;
}
}
}
(Untested code)

Can't you just go like this :
for (int i = 0; i < N ; i++) {
if (i%2 == 0)
{
cout << "**" << endl;
}
else
{
cout << "*" << endl;
}
}
In your case, for each of your N iterations, you print , jump to a new line, print *, and then jump to a new iteration. So 14 lines when N is 7.

It's because each time the first for loop runs, the second loop also runs. You can't print out both * and ** and expect it to print N times (it will always print 2 * N times). You need to print either * or **, but not both at the same time. Simple example:
bool alternate = false;
for (int i = 0; i < N ; i++) {
if (alternate) {
cout << "*" << endl;
} else {
cout << "**" << endl;
}
alternate = !alternate;
}
You could remove the alternate variable and check if i is even or odd (with something like i & 1), but I used the alternate variable to help make it clearer.

For each complete iteration of your outer loop the following is printed:
*
**
If you run that loop 7 times then you'll get 14 rows. try this instead, no need for the inner loop:
for (int i = 0; i < N ; i++) {
cout << "*" << endl;
cout << "**" << endl;
}

Related

How to call a function to search an element an a 2D array?

I'm trying to get my homework done, but there is something is going wrong.
If a 2D array was in the main function, and I want to call a function, which its task is searching for an element in the 2D array, which the user enters the wanted element in the main function. If the wanted element was found, call a function to find its factorial then print the result in the main function, otherwise, call another function to show that the wanted element was not found.
I've tried the lines of code using Visual Studio 2019 as well as Dev C++.
My program does about 13 tasks which I organized them in a Switch Statement,
and the case of doing that task is Case number 9.
But once I enter the element I want to search in the console.
if the element existed in the array, the output always shows up like this:
"
Number 3 Found at position: 4
Factorial of 3 is: 6
3
"
whether the user entered 3 or else number.
Even if it was not found, the output is the same.
#include <iostream>
using namespace std;
// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);
// declaring a function to find the fatorial of the found element.
int fact_num(int);
// declaring a function to print out a searching error.
void search_error();
// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;
cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}
/**********************************************************************/
// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}
if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/
I expected the output of searching will be like this:
Example:
If the user entered the elements of the array as '1 2 3 4 5 6 7 8 9' and searched about the element '9'
IF THE WANTED ELEMENTS WAS FOUND:
the output will be :
"Number 9 Found at position: 4
Factorial of 9 is: 362880"
IF THE WANTED ELEMENTS WAS NOT FOUND:
the output will be :
"The wanted number was not Found in the array!"
You have undefined behaviour filling and searching the array
for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element
Array indices start from 0. If you want to display indices from 1, do arithmetic in the output
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

Program wont run to the end after function is called

I wrote a program to accept 15 integer values in an array, then pass this array to a function which will multiply each even index value by 4.
Currently the program displays the initial array, but seems like it's getting hung up before it displays the modified array.
Please help me understand why the program is getting stuck here!
int main(){
const int SIZE = 15;
int quad[SIZE] = {};
void quadruple(int[], const int);
cout << "Enter 15 integer values into an array." << endl;
for (int i = 0; i < SIZE; i++) // Accept 15 int values
{
cout << i << ": ";
cin >> quad[i];
}
cout << "Before quadruple function is called: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
quadruple(quad, SIZE);
cout << "After even index value multiplication: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << quad[i] << " ";
}
cout << endl;
return 0;
}
void quadruple(int values[], const int SZ){
for (int i = 0; i < SZ; i + 2) // Multiply even values by 4
{
if ((i % 2) == 0)
{
values[i] = values[i] * 4;
}
else // Keep odd values the same
{
values[i] = values[i] * 1;
}
}
}
for (int i = 0; i < SZ; i + 2)
"i + 2" doesn't do anything.
You probably meant "i += 2;".
Your homework assignment is to find some documentation about your system's debugger. And find where your rubber duck is, as it's been suggested in the comments.

Recursively printing a star pattern

For my c++ data structures class our assignment is to print a pattern of stars like this
*
* *
* * *
* * * *
* * * *
* * *
* *
*
with the number of lines in the pattern determined by the user input. So the pattern above would print if the user enters a 4.
We had a previous assignment where we had to print the opposite pattern, one like this
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
and the above pattern would print if the user enters a 5. This pattern, the one above, I had no problem with. I used a for loop to print the top half, then recursively called the function again, and then the same for loop to print the bottom half in the opposite direction. For reference, here's the code I used for the above pattern:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
} // end of main
void printStars(int num)
{
if (num < 0) cout << endl << "Please enter a non negative number." << endl;
else{
if (num == 0) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num - 1);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
} // end printStars
This function works like how I want it, so I figured I would use it as a reference to complete the second assignment. The problem I'm having is that, while it was easy enough to complete the first assignment (printing a line of 4 stars, then a line of 3, then a line of 2 , then a line of 1, then all that again in reverse order), I can't seem to figure out how to format the for loops to print the pattern starting with a line of 1 star, then a line of 2, then a line of 3, and so on, until its called recursively and printed again in reverse order.
For reference, this is the code I have (so far) for the second assignment:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number, 0);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
void printStars(int num, int num2)
{
if (num2 <= num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
}
}
The only thing this prints is the second half of the pattern;
(If the user enters a 5)
* * * * *
* * * *
* * *
* *
*
And even to make this work, I have to recursively call the function at the end, which is out of order.
I guess I'm just confused on how this recursion is supposed to work but I've been playing with it for hours and I can't seem to reformat it or rearrange it or restructure it so that it prints like I need it to. Can someone give me some guidance? Just maybe write some pseudo code to help me out. This is for school so I need to be able to understand it but I'm really lost right now.
Try this. It is minimally modified version of your code. The upper limit is passed to all recursions and the recursive function calls are performed with the values starting with 1 (only 1 start in the first line):
void printStars(int num, int limit)
{
if (num >limit) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num +1, limit);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
int main()
{
int number=5;
cin>>number;
printStars(1, number);
return 0;
} // end of main
I tested it and the result is correct. The link is:
http://ideone.com/ez6pZ5
ideone result:
Success time: 0 memory: 3144 signal:0
*
**
***
****
*****
*****
****
***
**
*
For the sake of the exercise - how about a recursive function to print the stars and another to determine the number of stars:
string ReturnStars(int number)
{
if (number > 1)
return "*" + ReturnStars(number -1);
return "*";
}
void PrintStars(int start, int lines)
{
cout << ReturnStars(start) << endl;
if (start < lines)
PrintStars(start + 1, lines);
cout << ReturnStars(start) << endl;
}
int main()
{
int numberLines = 1;
cout << "Please enter a positive number to print a star pattern for: ";
cin >> numberLines;
PrintStars(1, numberLines);
return 0;
}
Example of output:
I suggest using two recursive functions, one to print in increasing order and the other to print in decreasing order.
After you get the two functions working, save a copy of the program.
You can then try to create one function the performs both increasing and decreasing orders of stars.
You aren't printing out the stars after your recursion call:
void printStars(int num, int num2)
{
if (num2 < num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
}
}
note the if condition had to change slightly too. I also agree with Thomas, it might make more sense to structure your recursion differently:
void printStars(int num)
{
for (int i = 1; i <= num; i++)
{
cout << "*";
}
cout << endl;
}
void printStarsRecursive(int stars)
{
if (stars == 0)
return;
printStars(stars);
printStarsRecursive(stars-1);
printStars(stars);
}
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStarsRecursive(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
If you want to do it recursively, you have to keep in mind that there are multiple states: the state where you're counting up to N, and the state where you're counting back to 1. So if you have to go it recursively, you need to keep track of those extra things:
void printStarsImpl(int count, int initial, int sign)
↑ ↑ ↑
current termination next step
And this function just has to know which next printStarsImpl() function to call - whether we just call with count + sign, whether we flip sign to -1, or whether we do nothing... all after printing count *'s of course.
The initial call is then:
void printStars(int n) {
printStarsImpl(1, n, +1);
}
The straightforward approach if to use the function declared as having only one parameter is the following with using a static local variable in the function
#include <iostream>
void print_stars( size_t n )
{
static size_t m;
if ( m++ != n )
{
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
print_stars( n );
}
--m;
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The program output can look like
Enter a non-negative number (0-exit): 4
*
**
***
****
****
***
**
*
Enter a non-negative number (0-exit): 3
*
**
***
***
**
*
Enter a non-negative number (0-exit): 2
*
**
**
*
Enter a non-negative number (0-exit): 1
*
*
Enter a non-negative number (0-exit): 0
If you do not want to use a static variable within the recursive function then instead of it you can apply a trick with standard stream member function width. In this case the recursive function will look the following way
#include <iostream>
#include <iomanip>
void print_stars( size_t n )
{
std::streamsize m = std::cout.width();
if ( m++ != n )
{
std::cout.width( m );
std::cout << std::setfill( '*' );
std::cout << '*' << std::endl;
std::cout.width( m );
print_stars( n );
}
std::cout.width( m-- );
std::cout << std::setfill( '*' );
std::cout << '\n';
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The output will be the same as above.
P.S. It seems that the only programmer who is able to write the function is me unemployed.:) All others are unable to do this assignment for beginners.:)
I think the best answer should be if only one recursive function is used -
#include <iostream>
using namespace std;
void recursive(int current, int lastEnter, int limit, bool isLimitReached) {
cout << "*";
if(current == lastEnter ) {
cout << endl;
current = 0;
if(isLimitReached == false)
lastEnter++;
else lastEnter--;
}
if(current + 1 == limit) {
isLimitReached = true;
}
current++;
if(!(isLimitReached == true && lastEnter == 0))
recursive(current, lastEnter, limit, isLimitReached);
}
int main()
{
int num = 0;
cout << "Enter max number of stars to be generated : ";
cin >> num;
recursive(1, 1, num, false);
return 0;
}
The code above uses only one recursive function without for/while loops.
output -
Enter max number of stars to be generated : 6
*
**
***
****
*****
******
*****
****
***
**
*

Simple C++ Program with Multidimensional Array Errors?

When running the following code, I am attempting to update a Tic Tac Toe game board.
When you type in 3 as a column, it sets 2 X's or O's in the game board.
Here is an example of the output
* * *
* * *
* * *
X: Select a Row: 1
X: Select a Col: 3
* * X
X * *
* * *
Here is the desired output
* * *
* * *
* * *
X: Select a Row: 1
X: Select a Col: 3
* * X
* * *
* * *
Here is the code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int rowSelect = 0;
int colSelect = 0;
char turn = 'X';
char rowcol[2][2];
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
rowcol[i][j] = '*';
}
}
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
cout << rowcol[i][j] << " ";
}
cout << endl;
}
cout << endl;
while (true)
{
cout << turn << ": Select a Row: ";
cin >> rowSelect;
while (rowSelect < 1 || rowSelect > 3)
{
cout << "I cannot accept that value, try again!" << endl;
cout << endl;
cout << turn << ": Select a Row: ";
cin >> rowSelect;
}
cout << turn << ": Select a Col: ";
cin >> colSelect;
while (colSelect < 1 || colSelect > 3)
{
cout << "I cannot accept that value, try again!" << endl;
cout << endl;
cout << turn << ": Select a Col: " << endl;
cin >> colSelect;
}
rowcol[rowSelect-1][colSelect-1] = turn;
if (turn == 'X')
{
turn = 'O';
}
else
{
turn = 'X';
}
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
cout << rowcol[i][j] << " ";
}
cout << endl;
}
}
system("PAUSE");
return 0;
}
Thanks!
-Mike
The problem is the array. Although arrays are accessed using zero based indices, the definition requires the actual number of elements for which to reserve space.
You defined rowcol as:
char rowcol[2][2]; // This defines a 2 x 2 array
You should have defined rowcol as:
char rowcol[3][3]; // This defines a 3 x 3 array
Hope this helps!
Keith
Your rowcol array needs to be 3x3:
char rowcol[3][3];
char rowcol[2][2];
In all the cases, i, j must iterate only until < 2 since it is a 2x2 array.
Your array only holds 2 elements per row, while your loop runs through three rows and three columns. You seem to be confused on how arrays are numbered, an array with 2 elements would be accessed using elements[0] and elements[1], because 0 is the first number in programming(not 1). you need to declare an array of THREE elements, and access them using [0] [1] and [2].
FIX: change to char Array[3][3];

How to refactor this simple code to avoid code duplication?

I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition.
Input:
10 // this is N, the number of the integers to follow
1 1 1 2 2 3 3 1 4 4
Output:
3 times 1.
2 times 2.
2 times 3.
1 times 1.
2 times 4.
Constraints:
All the numbers in the input(including N) are positive integer less than 10000.
Here is the code I got Accepted with:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
while(n --> 0) // do n times
{
cin >> currentNumber;
if(currentNumber != prevNumber)
{
if(currentCount != 0) //we don't print this first time
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else //if(currentNumber == prevNumber)
{
++currentCount;
}
}
cout << currentCount << " times " << prevNumber << "." << endl;
}
Now here's my problem. A little voice inside me keeps telling me that I am doing this line two times:
cout << currentCount << " times " << prevNumber << "." << endl;
I told that voice inside me that it might be possible to avoid printing separately in the end. It told me that there would then be perhaps way too many if's and else's for such a simple problem. Now, I don't want to make the code shorter. Nor do I want do minimize the number of if's and else's. But I do want to get rid of the special printing in the end of the loop without making the code more complicated.
I really believe this simple problem can be solved with simpler code than mine is. Hope I was clear and the question won't be deemed as not constructive :)
Thanks in advance.
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing
EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(4);
numbers.push_back(4);
for (int i=0; i<numbers.size(); i++)
{
int count = 1;
for (int j=i+1; j<numbers.size() && numbers[i] == numbers[j]; i++, j++)
{
count++;
}
cout << count << " times " << numbers[i] << "." << endl;
}
My version: reading the first value as a special case instead.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int value;
std::cin >> value;
--n;
while (n >= 0) {
int count = 1;
int previous = value;
while (n --> 0 && std::cin >> value && value == previous) {
++count;
}
std::cout << count << " times " << previous << ".\n";
}
}
Run your loop one longer (>= 0 instead of > 0), and in the last round, instead of reading currentNumber from cin, do currentNumber = lastNumber + 1 (so that it's guaranteed to differ).
slightly more CREATIVE answer, this one does not make assumption about input being all known before the start of the loop. This prints the total every time, but makes use of \r carriage return but not line feed. A new line is inserted when a different number is detected.
int prev_number = -1;
int current_number;
int count = 0;
for (int i=0; i<numbers.size(); i++)
{
current_number = numbers[i];
if (current_number != prev_number)
{
count = 0;
cout << endl;
}
count++;
prev_number = current_number;
cout << count << " times " << numbers[i] << "." << "\r";
}
only problem is that the cursor is left on the last line. you may need to append cout << endl;
I think this will work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
int i = 0;
while(i <= n)
{
if(i != n) cin >> currentNumber;
if(currentNumber != prevNumber || i == n)
{
if(currentCount != 0)
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else
{
++currentCount;
}
i++;
}
}
I would use a for loop, but I wanted to stay as close to the original as possible.