A four-digit password on your iPhone prevents unauthorized people from using your phone or stealing your information, but if you forget that passcode it prevents you from using your phone too. All is not lost if you’ve spaced on your passcode, however. You have three options to reset it, whether you’re near the computer you normally sync with or not.
Connect to iTunes
If the computer you normally sync your iPhone with is nearby, you can restore your phone with iTunes. Connect your iPhone to the computer with the USB cord and open iTunes. ITunes will sync your phone and create a new backup. Once the sync is finished, restore your phone using the “Restore iPhone” button and enter a new passcode once the restore is complete.
Reset With Find My iPhone
If you’re away from your regular computer but have Find My iPhone enabled, you can still recover from a lost passcode. Using any computer, go to iCloud (link in Resources) and log in with your AppleID. Click “All Devices” at the top of the window, then select the phone with the forgotten password and click “Erase [device]” (where [device] is the name of your phone) to erase the phone and the passcode. From there, use the Setup Assistant on your phone to restore the most recent backup from iCloud.
Try Recovery Mode
If you can’t get to your own computer and haven’t set up Find My iPhone, it’s still possible to erase the phone and reset the passcode -- but you’ll be left without your stored data until you can get to your computer. Disconnect all the cables from your phone and power it down. Press and hold the Home button, then connect the phone to iTunes while continuing to hold the Home button down. Keep holding the Home button until you see the Connect to iTunes screen, then release it. When iTunes tells you it has detected a device in recovery mode, click "OK" and then restore your phone.
The Importance of Regular Backups
All of these methods of dealing with a forgotten password involve erasing the phone’s memory and restoring from your most recent backup. If you do not regularly sync and back up your phone, this will cause you to lose all data -- text messages, app data, notes, etc. -- the phone has saved since your last backup. When your phone is restored, make sure to choose a passcode you’ll easily remember but is hard for others to guess to avoid the problem in the future.