Get your own free workspace
View
 

Sequence_php

Page history last edited by Mike Leishman 4 years, 10 months ago

Sequence

 

The simplest computer programs are those which require only a number of separate sequenced steps. In this section you will plan and write computer programs for problems requiring a solution of this kind where you will get data as input from the user, do some processing on that data and then output information back to the user.

 

Typical of these programs are as follows:

 

Get a number and perform some calculation

 

<?php

//Age calculation program written in PHP and designed for use at the command line

// input

fwrite(STDOUT, "What year is it now? eg 2007 -> ");

fscanf(STDIN, "%d\n", $year);

fwrite(STDOUT, "What year were you born in? eg 1999 -> ");

fscanf(STDIN, "%d\n", $born);

// processing

$age = $year - $born;

// output

fwrite(STDOUT, "You are ".$age." years old\n");

exit(0)

?>

Note

 

Get a character such as Y for yes, or N for N

 

 <?php

//get a character program written in PHP and designed for use at the command line

// input

fwrite(STDOUT, "are you male (M) or female (F) -> ");

fscanf(STDIN, "%c\n", $gender);

// processing

//none

// output

fwrite(STDOUT, "You entered ".$gender."\n");

exit(0)

?>

Note

fscanf(STDIN, "%c\n", variable) allows input of the value of the variable. http://au.php.net/fscanf

The "%c determines the data type as character. http://au.php.net/manual/en/function.sprintf.php 

 

Get a word of a sentence and include it in a sentence

<?php

//get a character program written in PHP and designed for use at the command line

// input

fwrite(STDOUT, "enter a noun -> ");

fscanf(STDIN, "%s\n", $noun);

fwrite(STDOUT, "enter a verb -> ");

fscanf(STDIN, "%s\n", $verb);

fwrite(STDOUT, "enter an adjective -> ");

fscanf(STDIN, "%s\n", $adjective);

// processing

//none

// output

fwrite(STDOUT, $noun." ".$verb." ".$adjective."\n");

exit(0)

?>

 

Note

fscanf(STDIN, "%s\n", variable) allows input of the value of the variable. http://au.php.net/fscanf

The "%s determines the data type as string. http://au.php.net/manual/en/function.sprintf.php 

 

Exercises

  1. Churchland Fencing Contractors charges customers $74 per metre for Trim-Lock fencing and $49 per metre to erect it. Churchland Fencing has contracted you to write a computer program using PHP that will calculate the cost of supplying and installing a new fence. Design and write the program that could be used for this purpose.
  2. Write a program that allows the user to enter his/her given name, middle initial, surname, gender and age, and then display it in the following order - Surname, Given Name Initial <age> <gender>.  eg enter Bill and then Jones, and then C, and then 16 and then M to display Jones, Bill C <16> <M>
  3. <Please add more>

 

 

Comments (0)

You don't have permission to comment on this page.