15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

534<br />

Creating Functions<br />

If you don’t know how many times you need to repeat commands, you’ll<br />

have to use a WHILE loop, which looks like this:<br />

while (condition) {<br />

Command;<br />

}<br />

If the condition is True, the loop runs at least once. If this condition is<br />

False, the loop does not run.<br />

A variation of the WHILE loop is the DO-WHILE loop, which looks like this:<br />

do {<br />

Command;<br />

} while (condition);<br />

The main difference between the two loops is that the WHILE loop may run<br />

zero or more times, but the DO-WHILE loop always runs at least once.<br />

Somewhere inside a WHILE and a DO-WHILE loop, you must have a command<br />

that can change the condition from True to False; otherwise, the<br />

loop will never end, and your program will appear to hang or freeze.<br />

Creating Functions<br />

In C/C++, every subprogram is a function that can return a value. The <strong>for</strong>mat<br />

of a typical function looks like this:<br />

Datatype functionname (Parameter list)<br />

{<br />

Commands;<br />

Return value;<br />

}<br />

The three parts of a C/C++ function are<br />

✦ Data type: Defines the type of value the function returns, such as an<br />

integer (int) or a floating point number (float). If you don’t want a<br />

function to return a value, declare its data type as void. This makes the<br />

function act like a procedure in other <strong>programming</strong> languages.<br />

✦ Parameter list: Defines any data and their data types that the function<br />

needs to work.<br />

✦ Return: Defines a value to return. This value must be the same data type<br />

specified right be<strong>for</strong>e the function name.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!