I can figure out what is wrong with this simple sketch

Read the link provided by @ilguargua.
It explains in detail

However most beginners just make all variables global and declare them at the top of the program outside of setup and loop, that way they can be used inside both setup and loop