A02.m - Period of a Pendulum

% Tidy up the workspace
clc         % clear command window
clear       % clear all variables
close all   % close all graphics windows

g = 9.8;    % define acceleration of gravity in MKS units

% prompt user to enter the length of a pendulum
L = input('Enter length of pendulum (in meters):  ');

% calculate the period
P = 2*pi*sqrt(L/g);

% the first fprintf statement prints a blank line to space things out.
% the second fprintf statement prints the period of the pendulum in command
% window and specifies that 3 sig figs should be displayed.
fprintf('Period = %.3g seconds\n',P)

Download A02.m

This program demonstrates how to prompt the user for information and how to display quantitative results in a controlled way using fprintf. The fprintf command is common to many programming languages including C and C++. It provides a way of controlling the number of significant digits displayed and whether the number is written in scientific notation or not. The first argument of the fprintf() command is a string that controls the fomatting of the displayed number. See the examples below to see how this works. The \n character adds a carriage return so the next print statement starts on a new line. Try monkeying around with these examples

Monkey Home   |    Prev   |   Next