Recursively printing a star pattern - c++

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
*
**
***
****
*****
******
*****
****
***
**
*

Related

Program to print Factorial of a number in c++

Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Problem: I am able to print the result,but not able to print like this :
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
My Code:
# include <bits/stdc++.h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= ++i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}
I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;
That's indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.
This should only be an idea this is far away from being a good example but it should do the job.
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i++)
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
Better approach using std::string and std::stringstream
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i++)
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}

Continuous x no. of A and then after (n-x) no.s of B

I am stuck in one of the problem related string in c++. My logic has worked well for some test cases, but not for all test cases. Please suggest me the actual logic of the following question::
I am given a string s of n character, comprising only of A's and B's . I can choose any index i and change s(i) to either A or B. Find the minimum no. Of changes that you must make to string S such that the resultant string is of format : AAAAA.....BBBBB. In other words, your task is to determine minimum no. of changes such that string s has x no. of A's in the beginning, followed by the remaining (n-x) no. of B's.
my code::
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, i, flag = 0;
cin >> n;
string str;
cin >> str;
int cnt = 0, cnt1 = 0;
for (i = 0; i < str.length(); i++) {
if (str[i] == 'A') {
cnt++;
} else {
cnt1++;
}
}
int pp = 0;
//cout << cnt << " " <<cnt1;
for (i = 0; i < cnt; i++) {
if (str[i] == 'B') {
pp++;
}
}
for (i = cnt; i < n; i++) {
if (str[i] == 'A' && str[i - 1] != 'A') {
pp++;
}
}
cout << pp << endl;
}
}
For example: AAB = 0 changes, BABA= 2 changes , AABAA= 1 changes
How to approach this question. Do respond!!!
I wrote the following code to compute the number of changes needing to order a string containing unorderd A e B according to the order that shall be "A[...A]B[...B]". (function countChanges).
The algorithm (countChanges) used to count modifications acts in three steps:
Step 1: counts how much 'A' chars are in the string (cnt).
Step 2: scans how much 'B' chars are in the first cnt chars of the string increasing a counter (sum) for each encounterd 'B'.
Step 3: scans how much 'A' chars are in the remaining chars of the string after the 2nd step increasing a counter (sum) for each encountered 'A'.
At the end of the function sum is the expected result.
The code also computes and executes the minimum number of swaps needing to obtain the string ordered according to the requirement.
The code contains two evaluation functions (the code under the main):
cntChanges. It computes the needing number of changes (The code gives the result as foreseen changes).
executeSwaps. It performs swaps on the string, counts them and may or may not show the steps performed.
Code result:
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit y
Insert your code? BABA
Do you want to print swap steps? [y]es/[n]o y
Input: BABA
Step 1 BABA swap(3,0) ==> AABB
Result AABB performed with 1 swap - foreseen changes 2
--
Do you have a code composed of A and B? [y]es/[n]o/[I] do it/[q]uit n
How much codes do you want to generate? 5
What's your preferred length for all generated codes? 10
Do you want to print swap steps? [y]es/[n]o y
Input: AAAAABAABB
Step 1 AAAAABAABB swap(7,5) ==> AAAAAAABBB
Result AAAAAAABBB performed with 1 swap - foreseen changes 2
--
Input: ABBABAAABA
Step 1 ABBABAAABA swap(9,1) ==> AABABAAABB
Step 2 AABABAAABB swap(7,2) ==> AAAABAABBB
Step 3 AAAABAABBB swap(6,4) ==> AAAAAABBBB
Result AAAAAABBBB performed with 3 swaps - foreseen changes 6
--
Input: AAABBAABBB
Step 1 AAABBAABBB swap(6,3) ==> AAAABABBBB
Step 2 AAAABABBBB swap(5,4) ==> AAAAABBBBB
Result AAAAABBBBB performed with 2 swaps - foreseen changes 4
--
Input: BABAABBABB
Step 1 BABAABBABB swap(7,0) ==> AABAABBBBB
Step 2 AABAABBBBB swap(4,2) ==> AAAABBBBBB
Result AAAABBBBBB performed with 2 swaps - foreseen changes 4
--
Input: AAABAABAAA
Step 1 AAABAABAAA swap(9,3) ==> AAAAAABAAB
Step 2 AAAAAABAAB swap(8,6) ==> AAAAAAAABB
Result AAAAAAAABB performed with 2 swaps - foreseen changes 4
--
The code:
#include <iostream>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
unsigned int executeSwaps(string &x, bool printSteps);
unsigned int cntChanges(const string& x);
unsigned int cntChangesJarod42(string const &x);
unsigned int cntChangesDamien(string const &x);
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x);
string generateCode(size_t n);
const char char1='A';
const char char2='B';
int main(void)
{
srand(static_cast<unsigned int>(time(nullptr)));
int c;
size_t cl;
char ync='n';
char ynps='n';
string x;
x.clear();
do {
questionToStart(c,cl,ync,ynps,x);
if (ync == 'q')
break;
for(int i=0;i<c;i++) {
unsigned int cnt=0;
if (ync=='n') {
x=generateCode(cl)
}
/* unsigned int fc2 = cntChangesJarod42(x);
unsigned int fc1 = cntChangesDamien(x);*/
unsigned int fc3 = cntChanges(x);
cout << "Input: " << x << endl;
cnt=executeSwaps(x, (ynps=='y')?1:0);
cout << "Result " << x << " performed with "
<< ((cnt>0)?to_string(cnt):"no")
<< " swap"
<< ((cnt>1)?"s ":" ") << " - foreseen changes " << fc3 << endl << "--" << endl;
/* << "foreseen changes (#Damien) " << fc1
<< " - foreseen changes (#Jarod42) " << fc2
<< endl << endl;*/
}
} while(ync != 'q');
return 0;
}
unsigned int cntChanges(const string& x)
{
const char * s;
unsigned int cnt=0,sum=0,i;
if (x.empty())
return 0;
s=x.c_str();i=0;
// count char1
while(*(s+i))
if (*(s+i++) == char1)
cnt++;
/* verify how much elements, from start to cnt,
* are different than char1 (equal to char2).
*/
for(i=0;i<cnt;i++)
if (*(s+i)==char2)
sum++;
cnt=static_cast<unsigned int>(strlen(s));
/* verify how much of the remaining elements
* are different than char2 (equal to char1).
*/
for(;i<cnt;i++)
if (*(s+i)==char1)
sum++;
return sum;
}
// #Jarod42
unsigned int cntChangesJarod42(const string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
unsigned int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return static_cast<unsigned int>(*std::min_element(switch_count.begin(), switch_count.end()));
}
// #Damien Algorithm
unsigned int cntChangesDamien (string const &x)
{
size_t n = x.length();
int cntCh_1 = 0, cntCh_2 = 0;
// there's nothing to swap!! :p
if (n < 2)
return 0;
for (size_t i = 0; i < n; ++i) {
if (x.at(i) == char1) {
cntCh_1++;
} else {
// x.at(i) is equal to char1
cntCh_1 = min (cntCh_2, cntCh_1);
// Now the foreseen swap are equal to cntCh1
cntCh_2++;
}
}
return static_cast<unsigned int>(std::min (cntCh_2, cntCh_1));
}
unsigned int executeSwaps(string &x, bool printSteps)
{
unsigned int cnt =0;
size_t apos=0;
size_t bpos=0;
// cout << "Start: " << x << " " << apos << " " << bpos << endl;
do {
apos=x.find_last_of(char1);
if (apos == string::npos)
break;
bpos=x.find_first_of(char2);
if (bpos == string::npos)
break;
if (apos>bpos) {
++cnt;
if (printSteps) {
cout << "Step " << cnt << " " << x << " swap(" << apos << "," << bpos <<") ==> ";
}
x.at(bpos)=char1;
x.at(apos)=char2;
if (printSteps)
cout << x << endl;
}
} while(apos>bpos);
return cnt;
}
string generateCode(size_t n)
{
string x;
x.clear();
size_t i,cb=0;
char ch;
if (n==0) {
n=rand()%10;
}
for (i=0;i<n-1;i++) {
ch = ( char1 + (rand()&1) );
if (ch == char2 )
cb++;
x +=ch;
}
if (cb==n-1) {
ch=char1;
} else if (cb==0) {
ch=char2;
} else {
ch=( char1 + (rand()&1) );
}
x += ch;
return x;
}
void questionToStart(int &c, size_t &cl, char &ync, char &ynps, string &x)
{
int ex=1;
do {
ex=1;
cout << "Do you have a code composed of "<<char1 << " and " << char2 <<"? [y]es/[n]o/[I] do it/[q]uit ";
cin >> ync;
switch(ync) {
case 'n':
cout << "How much codes do you want to generate? ";
cin >> c;
cout << "What's your preferred length for all generated codes? ";
cin >> cl;
break;
case 'I':
c=10; cl=(rand()&7)+9;
cout << c <<" attempts with " << cl << " characters long strings will be executed" << endl;
break;
case 'y':
c=1;
cout << "Insert your code? ";
cin >> x;
cl = x.length();
break;
case 'q':
break;
default:
ex=0;
}
} while(!ex);
if ( ync != 'q' ) {
if ( ync != 'I' ) {
cout << "Do you want to print swap steps? [y]es/[n]o ";
cin >> ynps;
} else {
ynps = 'y';
ync = 'n';
}
cout << endl;
}
}
As state by Tfry,
you might count the number of switch needed to have
XBBB
AXBB
AAXB
AAAX
which is the number of 'B' before the index + number of 'A' after the index.
Then take the minimum:
std::size_t count_switch_for_ab(const std::string& s)
{
if (s.empty()) { return 0; }
std::vector<std::size_t> switch_count(s.size());
{ // Count 'B' before index
int sum = 0;
std::size_t i = 0;
for (auto c : s) {
switch_count[i++] += sum;
sum += c == 'B';
}
}
{ // Count 'A' after the index
int sum = 0;
std::size_t i = 0;
for (auto c : std::string(s.rbegin(), s.rend())) {
switch_count[s.size() - 1 - i++] += sum;
sum += c == 'A';
}
}
return *std::min_element(switch_count.begin(), switch_count.end());
}
Demo.
The solution can be found in a simple loop, considering a 2-state process.
A state corresponds to the fact that for the given index, we decide to be in the A part or the B part. The transition from B state to A state is not allowed.
The corresponding number of changes up to index i can then be calculated iteratively.
For index i, let us call countA[i] the number of changes to get A only until index i, and let us call countB[i] the optimal number of changes up to i, assuming that somewhere before i, or at i time, we decided that the following part of the last string will containt B only.
It the current character s[i] is equal to A, then
countA[i] = countA[i-1]
countB[i] = countB[i-1] + 1
If the current character is B, then
countA[i] = countA[i-1] + 1
countB[i] = min (countB[i-1], countA[i-1])
if the last equation, countB[i] = countB[i-1] corresponds to the case that the transition to B state already occurs, and
countB[i] = countA[i-1] corresponds to the case that the transition occurs now.
In practice, we don't need an array to update countA and countB.
Here is the code:
#include <iostream>
#include <string>
int nb_changes (const std::string &s) {
int n = s.size();
if (n < 2) return 0;
int countA = 0, countB = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'A') {
countB++;
} else {
countB = std::min (countA, countB);
countA++;
}
}
return std::min (countA, countB);
}
int main() {
std::string s;
s = "AAB";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "BABA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
s = "AABAA";
std::cout << "number of changes for " << s << " is " << nb_changes(s) << "\n";
}

find the each number of 4 digit of user input and count it using recursion

I have with my code. This is about recursion. I have to create function digitAppear( int findDigit, int value) where value is the user input, and findDigit is single digit number ranging from 0 to 9. The function read user input and return each digit number from the user input and count how many times each digit number occurs in the user input. For example, if I type 1234 then the output say 1 appear 1 time, 2 appear 1 time and so on (I hope my explanation is clear) The problem is the only run once and can only return 1 value.
#include <iostream>
using namespace std;
int countOccurence(int, int);
int main()
{
int findDig;
int value;
int n = 0;
cout << "Please enter a positive number: " << endl;
cin >> value;
cout << "The value is " << value << endl;
while ((value < 0) || (value > 9999))
{
cout << "Invalid value. Please try again!" << endl;
cout << "Please enter a positive number: " << endl;
cin >> value; //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
}
//process the value
for (findDig = 0; findDig < 9; findDig++)
{
cout << endl;
cout << cout << "the " << findDig << "appear in digit " << value << " is " << countOccurence(findDig, value) << " times" << endl;
}
//countOccurance(findDig, value);
//cout
}
int countOccurence(int findDig, int value)
{
int n = value;
while( n > 10 )
{
int a = n / 10; //eliminate the right most integer from the rest
int aa = n % 10; //separate the right most integer from the rest
int b = a / 10; //eliminate the second integer from the rest
int bb = a % 10; //separate the second integer from the rest
int c = b / 10; // eliminate the third integer from the rest
int cc = b % 10; //separate the third integer from the rest
for (findDig = 0; findDig < 9; findDig++)
{
int i = 0;
if (findDig == aa) // see if the findDigit value is equal to single digit of b;
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == bb)
{
i += 1;
} else
{
i += 0;
}
return i;
if (findDig == cc)
{
i += 1;
} else
{
i += 0;
}
return il;
}
}
}
The problem is my function countOccurence() doesn't seems right. I wonder if there a way to do it. I have been stuck with this for days and I really appreciate your input, thank you.
To use recursion, you must think about the problem in a different way.
The easiest way of thinking about how you could incorporate recursion into the function is the process of 'peeling off' each number.
A very simple way of doing this is by looking at the first/last digit in the number, compute that, then call itself on the remainder of the number.
Hopefully you can figure out the code from there.
If you mean that function digitAppear itself has to be recursive then it can look the following way as it is shown in the demonstrative program below
#include <iostream>
#include <cstdlib>
size_t digitAppear( int findDigit, int value )
{
return ( std::abs( value ) % 10u == std::abs( findDigit ) ) +
( ( value /= 10 ) ? digitAppear( findDigit, value ) : 0 );
}
int main()
{
int i = 0;
for ( int x : { 0, 11111, 1234, 34343 } )
{
std::cout << "There are " << digitAppear( i, x )
<< " digit " << i
<< " in number " << x
<< std::endl;
++i;
}
return 0;
}
The program output is
There are 1 digit 0 in number 0
There are 5 digit 1 in number 11111
There are 1 digit 2 in number 1234
There are 3 digit 3 in number 34343
Of course you may rewrite function main as you like for example that it would count each digit in a number.

Recursively print Factorial values in decreasing order?

Using C++ to figure out the factorial is straightforward enough. To print the values coming up (if factorial is 5) ... 1 * 2, * 3, * 4 * 5 also no problem - as I think I've done below.
But what I'm having a hard time doing is saying show me 5 * 4 then value * 3 then value * 2 etc. I want to be able to print the data going down and I can't seem to figure it out.
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
}
There are a couple of other posts but I didn't find one asking the same thing.
The desired results are: 20 60 120
The current results are 1 2 6 24 120
Please advise.
Thank you.
Just change where you are printing the value
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
to
else
{
cout << " going down" << n << " ";
n = n * factorial(n - 1); // Recursive case
return n;
}
The above would print 5 4 3 2 1 but if you want something like
5 20 60 ...
Than you have to change the recursive definition a bit.
#include<iostream>
using namespace std;
int factorial(int n,int temp);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number,1) << endl;
}
int factorial(int n,int temp)
{
if (n == 0)
return temp; // Base case
else
{
cout << " going down" << n * temp << " ";
factorial(n - 1,n*temp); // Recursive case
//return n;
}
}

Simple Nested Loop Issue. * Shape *

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