How can I get rid of the first and last 0 in my code? | Sololearn: Learn to code for FREE!

+3

How can I get rid of the first and last 0 in my code?

Hey all! I come here once again asking for help 😅 I am attempting to write a program that asks for user input of a positive integer larger than 2. The program is supposed to output all the positive integers that are smaller than the user input and that are multiples of 3. However, when running my code I noticed there are two annoying 0’s that keep appearing and aren’t supposed to be there. Any help on how to remove them or make the code better? Thank you! https://code.sololearn.com/cQ3NUjm3g7f6/?ref=app

c++

1/26/2022 11:56:14 PM

Annei ❤️

7 Answers

New Answer

+4

You're welcome! Remember to add return 0; in your main function, this is like a standard thing to do. Also when you have a function and don't want it to return anything define it as: void <function_name>() { } That function doesn't have a return value but it can do stuff like your function there for example printing something on the screen.

+5

The first 0 is from your for loop. You start with i = 0 and then print it on the screen. The last 0 is from return statement (return 0;). Your function returns 0 after finishing the for loop. That is why your code has 0 at the beginning and at the end of the output.

+1

Thank you!! Though, I tried replacing it with 1 but it replaces it with 1. So I am a bit stuck on how to fix the 0 in the loop. It cant work without an intilizer and return is to be there?

+1

Also notice that your function prints something in the for loop and in your main function you are printing again but the value that is returned from the function which is 0. If you skip "cout<<" in main and just call the function, then the last 0 won't be printed :)

+1

Omg thank you sooo much!!

+1

G'day Annei ❤️ You can return the x from the function to remove the last 0. 🤭EDIT: Also gotta change the loop end to i<x-1 EDIT 2: Nope, leave the end condition as i<x remove cout<< from main(), leave the function call. You can start the loop at i=3 which will eliminate the first 0. Great looking code!

0

You can add an if statement to skip printing 0 :)