Call by reference (original value)
Nov 10, 2016 at 4:50am UTC
Is there a way to know what value n had for the first time?
I am unable to finish my code because I cannot give n the value it had at the beginning of the program.
In this program, n means the number of character there have to be to change line. My problem is that when n <= 0 since I am unable to give it the original value, the program will print a new line for each cycle.
Example (my program):
8
aiaiaiaiiii
.-...-..
.-
..
.-
..
..
..
..
STOP
Example (correct output):
.-...-..
.-...-..
......
STOP
I would be able to solve this by myself if there weren't these rules/restrictions.
RULES OF THE PROGRAM:
1. Cannot use arrays, vectors, algorithms or pointers
2. Use the function: void morse(char c, int& n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include<iostream>
using namespace std;
void morse(char c, int & n) {
if (c == 'a' ) {
cout << ".-" ;
n -= 2;
}
if (c == 'e' ) {
cout << "." ;
n -= 1;
}
if (c == 'i' ) {
cout << ".." ;
n -= 2;
}
if (c == 'o' ) {
cout << "---" ;
n -= 3;
}
if (c == 'u' ) {
cout << "..-" ;
n -= 3;
}
if (n <= 0) {
cout << endl;
}
}
int main () {
int n;
cin >> n;
char c;
bool loop = false ;
while (cin >> c) {
morse (c, n);
loop = true ;
}
if (loop) cout << endl;
cout << "STOP" << endl;
}
Last edited on Nov 10, 2016 at 4:54am UTC
Nov 10, 2016 at 5:02am UTC
Store it in a variable at the start of the function?
Nov 10, 2016 at 5:22am UTC
Explain better or put a code example, thanks
Last edited on Nov 10, 2016 at 5:26am UTC
Nov 10, 2016 at 7:23am UTC
I don't know what there is to explain in something basic such as storing a value in a variable.
1 2 3 4
void morse(char c, int & n) {
int orig = n;
// ...
}
Nov 10, 2016 at 9:42pm UTC
I cannot see how this
int orig = n;
would make my code work. In each cycle, origin will be the same as n, making me lose the original value of n.
Anyway, I got the answer of how to solve the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include<iostream>
using namespace std;
void morse(char c, int & n) {
if (c == 'a' ) {
cout << ".-" ;
n -= 2;
}
if (c == 'e' ) {
cout << "." ;
n -= 1;
}
if (c == 'i' ) {
cout << ".." ;
n -= 2;
}
if (c == 'o' ) {
cout << "---" ;
n -= 3;
}
if (c == 'u' ) {
cout << "..-" ;
n -= 3;
}
}
int main () {
int n;
cin >> n;
int aux = n;
char c;
bool loop = false ;
while (cin >> c) {
if (n <= 0) {
cout << endl;
n = aux;
}
morse (c, n);
loop = true ;
}
if (loop) cout << endl;
cout << "STOP" << endl;
}
Topic archived. No new replies allowed.