doing one of the challenges and I'm a little confused. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

doing one of the challenges and I'm a little confused.

I got the correct output after much tinkering but I'm not 100% sure how. I'm changing some of the stuff so it's not exactly the same and doesn't come up on google. void toPuppys(); void toPuppys(int dogs) { cin >> dogs; cout << dogs * 60; } int main() { toPuppys(1) ; return 0; } I was stuck on this for a minute. I knew what I wanted to do and how to do it. I'm just unsure as to why it worked specifically int main() { toPuppys(1) ; return 0; this part. for a while I had toPuppys(int dogs) ; and that didn't work and I was having issues on where to put the Cin >> dogs; in the code so I was messing around with it and I would get the right output if I removed the cin completely and used toPuppys(1) toPuppys(2) etc but I needed user input so I finally figured out I was putting cin in the wrong place and moved it to the void toPuppys(int dogs) { cin >> dogs; cout << dogs * 60; and it worked, but I had noticed I had left the int main() { toPuppys(1) ; return 0; as it was when I was using toPuppys(1) ; as my input. which is where I'm confused now. it works if I leave the 1 but if I leave it blank the program fails. I guess I just need this explained if any of this makes sense.

8th Jun 2021, 8:06 PM
Lexx
Lexx - avatar
4 Answers
+ 3
You have to think of your input and how it flows through your program. Put your cin statement in main() just above the toPuppys(). like this: int dogs; cin >> dogs; Now you have the necessary parameter so you can call your function. toPuppys(dogs); Remove the cin from the toPuppies function. Now, all that's going to happen is you will ask for # of dogs. Then pass that to toPuppies. Then it will output dogs * 60. The program will end.
8th Jun 2021, 8:36 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
Variables have scope. Visibility. You’ll have to learn that global variables can be seen anywhere, but that’s bad programming form. Better is local variables, but they aren’t visible in other scopes. So you pass them as needed. Ideally a function will only have access to variables it needs and those are passed back and forth as needed.
8th Jun 2021, 9:29 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
That helps so much and this makes sense now thank you.
8th Jun 2021, 9:37 PM
Lexx
Lexx - avatar
0
Okay so I did try that earlier however I did not declare Int dogs; in my main function. since I declared it in my void statement. Why do I have to declare it in my main function as well?
8th Jun 2021, 9:26 PM
Lexx
Lexx - avatar