c++ output of stars using recursion - c++

I am trying to do this exercise.
Write a recursive function to generate a pattern of stars such as the following:
*
**
***
****
****
***
**
*
It seems simple but is giving me a lot of problems. I can only output this
*
**
***
****
using the following code
#include <iostream>
using namespace std;
void outputStars(int);
int main()
{
outputStars(5);
return 0;
}
void outputStars(int num)
{
if (num == 1)
{
return;
}
outputStars(--num);
for (int i = 0; i < num ; i++)
{
cout << "*";
}
cout << endl;
}

You are only printing the stars when you return from the call. Also print it before you call.
I've modified it to take 2 arguments. i specifies number of times * is to be printed in a call
void outputStars(int num,int i)
{
if (i == num)
{
return;
}
for (int j = 0 ;j < i; j++)
{
cout << "*";
}
cout << endl;
outputStars(num,i+1);
for (int j = 0; j < i; j++)
{
cout << "*";
}
cout << endl;
Call it as
outputStars(5,1);

#include <stdio.h>
void rec_fun(int x);
void print_stars(int times, int x);
int main(int argc, char *argv[])
{
rec_fun(5);
return 0;
}
void rec_fun(int x)
{
static int times = x;
if (x <= 0)
return;
print_stars(times, x);
rec_fun(x - 1);
if (x != 1)
print_stars(times, x);
}
void print_stars(int times, int x)
{
int i;
for (i = 0; i < times - x + 1; i++)
printf("*");
printf("\n");
}

Related

Recursively storing integers in an array

I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}

Print opposite triangle recursion c++ in 1 function

I wonder if it is possible to print an opposite triangle (by "*") recursively using 1 function only.
for example
for the given base n=4
it should print
*****
***
**
*
*
**
***
****
I am a beginner, but I know how to program 1 recursive function for
*****
***
**
*
and one for
*
**
***
****
but is it possible to program 2 opposite triangles in 1 function?
Might be a stupid question that the answer of it is no- but I've been trying for an hour now and I could'nt make it.
I will be very thankful if you can let me know if it's even possible or not.
EDIT: My code for 2 different functions:
#include <iostream>
using namespace std;
void printOppositeriangle(int n);
void printOppositeriangle2(int n);
void main()
{
int n = 5;
printOppositeriangle(n);
printOppositeriangle2(n);
}
void printOppositeriangle(int n)
{
if (n == 0)
return;
else
{
for (int i = 0; i < n; i++)
cout << "*";
cout << endl;
printOppositeriangle(n - 1);
}
}
void printOppositeriangle2(int n)
{
if (n == 0)
return;
else
printOppositeriangle2(n - 1);
for (int i = 0; i < n; i++)
cout << "*";
cout << endl;
}
Simple enough, make your recursive call in the middle, before and after print out a row of asterisks.
void print(int n)
{
for (int i = 0; i < n; ++i)
cout << '*';
cout << '\n';
if (n > 1)
print(n - 1);
for (int i = 0; i < n; ++i)
cout << '*';
cout << '\n';
}
Untested code.

C++ Recursion to detect duplicates in row and column of grid

I'm coding a recursive algorithm to take a user input N and make a N x N grid where the same number does not appear twice on either a row or a column. Almost everything's working, and duplicates don't appear in columns, but I'm having trouble getting rows working.
My code for checking duplicates in rows is the function noRowDuplicates. Duplicates are still appearing, and occasionally it'll throw a segmentation fault, but I'm not sure why.
Thanks in advance for the help!
// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
cout << "Please enter a number!" << endl;
cin >> inputNum;
gridSize = inputNum * inputNum;
grid = new int[gridSize];
allOptions = new int[inputNum];
for (int i = 0; i < inputNum; i++) {
allOptions[i] = i + 1;
allOptionsSize++;
}
srand((unsigned)time(0));
fill(0);
delete[] grid;
delete[] allOptions;
return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
for (int i = 1; i < inputNum; i++) {
if (arrPosition - (inputNum * i) >= 0) {
if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
return false;
}
}
}
return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
int rowPosition = arrPosition % inputNum; // 0 to num - 1
if (rowPosition > 0) {
for (int p = 1; p < rowPosition; p++) {
if (grid[arrPosition - p] == valueToCheck) {
return false;
}
}
}
return true;
}
void fill(int arrayPosition) {
if (arrayPosition < gridSize) {
int randomPosition = rand() % allOptionsSize;
grid[arrayPosition] = allOptions[randomPosition];
if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
if (arrayPosition % inputNum == 0) {
cout << endl;
}
cout << grid[arrayPosition] << " ";
fill(arrayPosition + 1);
} else {
fill (arrayPosition);
}
} else {
fill(arrayPosition);
}
}
}
noRowDuplicates never tests the first element of a row, which makes sense when you are trying to fill the first element of a row, but not any other time.

Problems with terminating loop at specific time

Having trouble with my loop. The program is supposed to resemble a print out of a
lotto ticket. The user enters in how many sets of lotto numbers he/she wants. Each line is labeled alphabetically, yet if someone wants more then ten lines (letter J) of lotto numbers the program is supposed to start back over at A again. My problem is that if anyone enters 10 (or any interval of ten) "mega" gets printed like so:
"Mega" should only be printed again if there is another line of lotto numbers.
In "int main()" inside the "for()" is my attempt to remedy this problem.
#include <iostream> //I/O
#include <iomanip> //setw
#include <ctime> //seeding srand
#include <string> //size
#define RAND(a,b) (a+rand()% (b-a+1))
#define die(errmsg) {cerr << errmsg << endl; exit(1);}
using namespace std;
/*
Author: Zachary Stow
Date: July/20/15
Homework #5
Objective: To design a program that imitates the print out
of a lottery ticket.
*/
//********************************fillup()********************************
void fillup(int lotto[], int n, int from, int to)
{
void bubble_sort(int x[], int n);
for(int i = 0; i < n; i++)
{
lotto[i] = RAND(from,to);
}
bubble_sort(lotto,5);
}
//*****************************bubble_sort()******************************
void bubble_sort(int x[], int n)
{
for(int i = 0; i < n-1; i++)
{
int temp;
for(int j=i+1; j<n ; j++)
{
if(x[i] > x[j])
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
//********************************print()*********************************
void print(int x[], int n)
{
for(int i = 0; i < n; i++)
{
cout << setfill('0') << setw(2) << x[i] <<" ";
}
cout <<" ";
cout << setfill('0') << setw(2) << RAND(1,46);
cout << endl;
}
//********************************isNumber********************************
bool isNumber(string str)
{
for(int i = 0; i < str.size(); i++)
{
if(!isdigit(str[i]))return(false);
}
return(true);
}
//**********************************check*********************************
void check(int argc, char **argv)
{
bool isNumber(string);
if(argc != 2)die("usage: megaMillion number_tickets");
string num_tickets = argv[1];
if(!isNumber(num_tickets))die("Not a digit."); //removed num_tickets for now
int num;
num = atoi(num_tickets.c_str());
if(num <= 0)die("Zero or negative number."); //doesnt work
}
//*********************************printmega()****************************
void printmega(int letter)
{
if(letter == 65)
{
cout << endl;
cout <<" Mega" << endl; //10 you get a mega
}
}
//*********************************main()*********************************
int main(int argc, char **argv)
{
void fillup(int x[], int n, int from, int to);
void print(int x[], int n);
void check(int argc, char **argv);
void printmega(int letter);
check(argc, argv);
srand(time(NULL));
cout <<" Mega" << endl;
int letter = 65;
for(int i = 0; i < atoi(argv[1]); i++)
{
if(i == atoi(argc[1]))cout << "Hi"; //my attempt to stop the loop from printing
//only mega after J
cout <<(char)letter++; //when theres no more lines
cout <<" ";
if(letter == 75)letter = 65;
int lotto[5];
fillup(lotto,5,1,56);
print(lotto,5);
printmega(letter);
}
return(0);
}
For this problem I would choose to use two nested loops, here is a minimal example:
#include <iostream>
int main(int argc, char** argv)
{
double aValues[] = {1, 2, 3, 4, 5, 6, 7, 8, 6, 2};
int nTotalLines = sizeof(aValues)/sizeof(double);
int nLinesPerBlock = 5;
int nLineNumber = 0;
for (int i = 0; i <= nTotalLines/nLinesPerBlock
&& nLineNumber < nTotalLines; ++i)
{
std::cout << "Start of block..." << std::endl;
for (int j = 0; j < nLinesPerBlock && nLineNumber < nTotalLines; ++j)
{
std::cout << " Number: " << aValues[nLineNumber++] << std::endl;
}
}
return 0;
}
You will need to adapt this code to fit your problem. It is not necessary to use nested loops but to me it seems more logical (you cycle one outer loop for each block and one inner loop for each line).
Another tip: Make use of variables so you don't need to keep typing things like atoi(argv[1]), instead create a variable int name = atoi(argv[1]); and use name wherever you need it.

Why is my grapher printing multiple instances of the function? C++

I have this program that graphs simple parametric equations on a board of a defined length and width by me. It compiles fine but prints multiple instances of the function in different positions of the graph. If someone could please help me figure out why I am getting this output, I would greatly appreciate it. I included comments throughout the code to help understand what is going on.
I do not have enough reputation to post a picture of the output but if you compile and execute it you will see what I am talking about.
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <time.h>
#include <cmath>
using namespace std;
#define N 25
#define M 60
/*
This function prints the board each time it is called and places an *
in the place corresponding to the value of the function.
*/
void print_board(char p[M][N]) {
int i, j;
for (i=0; i<=N; i++) {
for (j=0; j<=M; j++)
if (i==0) cout << '=';
else if (j==0) cout << '|';
else if (i==N) cout << '=';
else if (j==M) cout << '|';
else if (p[i][j]== '*') cout << '*';
else cout << ' ';
cout << endl;
}
}
/*
These functions accepts an integer for time and computes a value for x and y
for the parametirc equations given and returns each.
*/
int fx(int t) {
int x = t;
return x;
}
int fy(int t) {
//int y = 5 * sin(0.2 * t) + 15;
int y = (pow(t,2)/60) - t + 25;
return y;
}
/*
This function copies the old board and comoputes what the new board is.
*/
void next_board(char p[M][N], int t) {
int i, j;
//copies the old board
int q[M][N];
for (i=0; i<=N; i++) {
for (j=0; j<=M; j++) {
q[i][j] = p[i][j];
}
}
//creates the new board
int x, y;
for (i=0; i<=N; i++) {
for (j=0; j<=M; j++) {
x = fx(t);
y = fy(t);
if (i == y && j == x) {
p[i][j] = '*'; //stores an * for the values of x and y
}
}
}
}
int main() {
char p[M][N];
print_board(p);
int t = 0;
while(t <= M) {
cout << string(80, '\n');
next_board(p , t);
print_board(p);
usleep(20000);
t++;
}
return 0;
}
Please help and thank you for all who try!
everywhere in your program where you have
char p[M][N]
change them to
char p[N][M]
and you should get the results that youd expect, your mixing axes in your program
heres the whole working code if youd like
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <time.h>
#include <cmath>
#include <string>
using namespace std;
#define N 25
#define M 60
/*
This function prints the board each time it is called and places an *
in the place corresponding to the value of the function.
*/
void print_board(char p[N][M]) {
int i, j;
for (i = 0; i <= N; i++) {
for (j = 0; j <= M; j++)
if (i == 0) cout << '=';
else if (j == 0) cout << '|';
else if (i == N) cout << '=';
else if (j == M) cout << '|';
else if (p[i][j] == '*') cout << '*';
else cout << ' ';
cout << endl;
}
}
/*
These functions accepts an integer for time and computes a value for x and y
for the parametirc equations given and returns each.
*/
int fx(int t) {
int x = t;
return x;
}
int fy(int t) {
//int y = 5 * sin(0.2 * t) + 15;
int y = (pow(t, 2) / 60) - t + 25;
return y;
}
/*
This function copies the old board and comoputes what the new board is.
*/
void next_board(char p[N][M], int t) {
int i, j;
//copies the old board
int q[M][N];
for (i = 0; i <= N; i++) {
for (j = 0; j <= M; j++) {
q[i][j] = p[i][j];
}
}
//creates the new board
int x, y;
for (i = 0; i <= N; i++) {
for (j = 0; j <= M; j++) {
x = fx(t);
y = fy(t);
if (i == y && j == x) {
p[i][j] = '*'; //stores an * for the values of x and y
}
}
}
}
int main() {
char p[N][M];
print_board(p);
int t = 0;
while (t <= M) {
cout << string(80, '\n');
next_board(p, t);
print_board(p);
usleep(20000);
t++;
}
return 0;
}