Pretext: I am new to c++ coding and know arrays and strings. This professor showed how to input and output into files and gave us the following assignment.
Assignment question: Input a number in a file. Now imagine there is a staircase with the inputted number of steps. You can either step up one step and denote this by 'u' or you can take two steps up and denote this by 'd'. Find all possible combinations of this type and write them in a file.
Example: For n=1 the output should be 'u'; For n=2 the output should be 'uu d'; For n=3 the output should be 'uuu ud du' and so on.
My thought process: So this is basically a Fibonacci series. So just like fibonacci series i thought of a recursive algorithm. Here is what I came up with...
Code
#include<iostream>
#include<fstream>
using namespace std;
void staircase(int num, int count, char* c, int index, ofstream &file)
{
char c1[num], c2[num];
for (int i = 0;i < num;i++) {
c1[i] = c[i];
c2[i] = c[i];
}
if (num - count == 2) {
c1[index] = 'd';
c2[index] = 'u';
c2[index + 1] = 'u';
file.open("output.txt", ios::app);
file << c1 <<" ";
file << c2 <<" ";
file.close();
return;
}
if (num - count == 1) {
c2[index] = 'u';
file.open("output.txt", ios::app);
file << c2 <<" ";
file.close();
return;
}
if (num - count > 2) {
c1[index] = 'd';
c2[index] = 'u';
staircase(num, count + 2, c1, index+1,file);
staircase(num, count + 1, c2, index+1,file);
}
}
int main(){
int num;
cout<<"Input total number of stairs: ";
cin>>num;
fstream myfile;
myfile.open("input.txt");
myfile<<num;
myfile.close();
cout<<"Input is saved in file Directory ";
char c[num];
ofstream file;
file.open("output.txt");
staircase(num, 0, c, 0, file);
}
Problem: When I wrote it without the file code and all it did fine and command prompt showed all the possible outputs. I also noticed for n=1 and n=2 it doesn't even print anything on the file. I feel like I'm missing somethings with fstream and cannot point it down. I tried to search google and stackoverflow. Thanks for helping me. Also following is the version without any files in it.
#include<iostream>
#include<fstream>
using namespace std;
void staircase(int num, int count, char* c, int index)
{
char c1[num], c2[num];
for (int i = 0;i < num;i++) {
c1[i] = c[i];
c2[i] = c[i];
}
if (num - count == 2) {
c1[index] = 'd';
c2[index] = 'u';
c2[index + 1] = 'u';
for(int i=0;i<=index;i++)
cout<<c1[i];
cout<<" ";
for(int i=0;i<=index+1;i++)
cout<<c2[i];
cout<<" ";
return;
}
if (num - count == 1) {
c2[index] = 'u';
for(int i=0;i<index+1;i++)
cout<<c2[i];
cout<<" ";
return;
}
if (num - count > 2) {
c1[index] = 'd';
c2[index] = 'u';
staircase(num, count + 2, c1, index+1);
staircase(num, count + 1, c2, index+1);
}
}
int main(){
int num;
cout<<"Input total number of stairs: ";
cin>>num;
cout<<"Input is saved in file Directory ";
char c[num];
staircase(num, 0, c, 0);
}