Anda di halaman 1dari 7

LAB 2

C PROGRAMMING TECHNIQUES
2.1. LAB OBJECTIVE
Lab 2 objectives include the following
More C programming techniques
Programming with loops (for loop, while loop etc.)
Use of arrays
The use of functions
Performing a numerical simulation in C and plotting the results using MATLAB
2.2. BACKGROUND
Review Chapter 17 of Mechatronics and the online C tutorial paying particular attention to
the following concepts
if statement
for loops
while statement
array declaration
function declaration
Adding comments to the program
2.2.1. break statement
The break statement can be used to exit from loops (for, while). The following two pro-
grams produce identical results
/* First program */
#include <stdio.h>
#include <conio.h> /* conio declares console i/o functions like
getch */
void main()
{
char a=a;
while(a != 'q') {
a = getch();
printf("You typed in %c\n", a);
}
}
/* Second program */
#include <stdio.h>
#include <conio.h> /* conio declares console i/o functions like
getch */
void main()
{
char a=a;
while(1) {
a = getch();
printf("You typed in %c\n", a);
if(a == 'q') break;
}
}
2.2.2. continue statement
The continue statement is used to bypass the remainder of the current pass through a loop.
The loop does not terminate when a continue statement is encountered. Rather,
the remaining loop statements are skipped and the computation proceeds to the next pass
through the loop.
For example, consider a program that prompts a user for an input and calculates the square
root of the number. Whenever a negative number is encountered we want to ignore the input.
#include <stdio.h>
#include <math.h> /* declares math functions */
void main()
{
int i;
double x,y;
for(i=0; i < 10; i++) {
printf("\n Enter a positive number: ");
scanf("%lf",&x);
if (x < 0.0) continue; /* ignore this dopes input */
y = sqrt(x);
printf(\nThe square root of %f is %f\n,x,y);
} /* end of for */
/* end of main */
2.2.3. Functions/Subroutines
Functions (a.k.a. subroutines) are used to break down a large program into a number of
smaller, self contained components each of which has some unique purpose. This is called a
modular programming approach. There are several advantages to this approach including
repeated access to a group of instructions
a different set of data can be transferred to the function each time it is accessed
more logical and clear programs
one can build a customized library of functions avoiding repetitive programming
between programs
For example, the following program utilizes a function called max, which returns the greater
of the two arguments passed to it. Note that functions should appear before the main
subroutine or should be declared using a function prototype. See the online tutorial for more
details on functions.
#include <stdio.h>
/* max returns the maximum of two values */
float max(float a, float b) {
if (a>b)
return(a);
else
return(b);
}
/* start of main main()
{
float x1=5., y1 = 10.;
float x2 = 15., y2 = 20.;
float z1, z2;
z1 = max(x1,y1);
z2 = max(x2,y2);
printf(\nThe greater of %f and %f is: %f \n,x1,y1,z1); printf(\nThe
greater of %f and %f is: %f \n,x2,y2,z2);
}
2.2.4. Debugging Tools: Single Stepping Through Programs
During the lab your TA will demonstrate how to use the debugging tool available with
Developer Studio. You will learn howto single step through a program and observe the values
of variables at different program execution stages. This can be an invaluable tool in debugging
your code and is much simpler than using printf statements to determine variable values.
Single step through the following program and note the values of num1, num2, &num1,
&num2 and pnum at each step of the program. Turn in these values with your postlab
report.
#include <stdio.h>
main()
{
int num1 = 5, num2 = 10;
int* pnum = NULL;
pnum = &num1;
*pnum +=10;
pnum = &num2;
num1 = *pnum;
}
2.3. PRELAB
Written hand in required.
1. The function sin(x) can be approximated by summing the first n terms of the infinite
series
sin(x) = x x
3
/3! + x
5
/5! x
7
/7! +
where x is expressed in radians (Note: radians = 180
o
).
Write a C program that can be used to answer the following questions during the lab:
a) For a value of x = 0.1, how many terms do you need in the power series so that the
result from the series equals the result from the sin(x) library function up to the 6
th
decimal place.
b) For a value of x = 1.3, how many terms do you need for achieving the same
accuracy as in (a)?
Assume that there exists a function double fact(int n) that returns the factorial value of an
integer as a double. This function will be given to you. There is a standard C function
double pow(double x, double y)
that returns the result of x to the power y as a double type. You will need to include
math.h to use this function (#include <math.h>).
2. Write a program that uses nested "for" loops to sort an array of integer numbers.
Input = [9 4 5 2 3 0 8 1 7 6];
Output = [0 1 2 3 4 5 6 7 8 9];
Hint: The on-line Ctutorial contains an example program that uses while loops.
3. Write a program to solve the RC-circuit shown below.
Write a program that calculates the capacitor voltage after the switch is closed. The capac-
itor is initially uncharged. Perform the simulation for a duration of five seconds. Use
DC
V =
0.5 volts
Steps:
1)
Write the differential equation for the circuit after the switch is closed. The
equation should be in terms of R, C, V
c
, and
DC
V
.
2)
Approximate the differential equation with a finite difference equation. Use the
first order forward difference equation
stepsize
(i) V 1) (i V
dt
dV
c c c

to approximate the derivative. Numerically solve the above difference equation for
V
c
(i+1).
3) Write a C program that iterates the difference equation and prints out the voltage
at each time instant.
Analysis:
a) Use a simulation time step of 0.1 seconds. Use the following values of R and C
a) R = 10,000 ohms, C = 0.0002F
b) R = 5,000 ohms, C = 0.0001F
b) Use a simulation time step of 0.5 seconds. Use the following values of R and C
a) R = 10,000 ohms, C = 0.0002F
b) R = 5,000 ohms, C = 0.0001F
2.4. LAB PROCEDURE
1. Implement the sin(x) series approximation program.
2. Implement the sorting algorithm program.
3. Implement the RC-circuit solution program.
Print the capacitor voltage at each instant of time on a newline.
The capacitor voltage values at different instants of time should be stored in a file. This file
will then be retrieved under MATLAB for plotting. This is done as follows:
Go to the DOS prompt for running the program.
Change to the project directory, such as lab2. The exe file is inside a directory called
debug. Change to this directory.
Z:> cd lab2\debug <CR>
At the command prompt type:
Z:> lab2 >> datafile <CR>
The >> command directs the output of the program lab2.exe into a file with the name
datafile.
To use this datafile in MATLAB type load at the MATLAB prompt. >>
Vc = load(datafile) <CR>
The command load calls a MATLAB function that reads in data from a file and stores the
data in array variable called Vc. You can use this variable for plotting the capacitor voltage
with respect to time. For plotting, create an array of time values beginning from 0 to 5 seconds
in 0.1 second increments (t = [0:0.1:5]). The MATLAB command plot(t,Vc)
will then produce the appropriate plot.
Note how quickly the voltage rises towards its final value in each of the two cases (a) and (b)
for both simulation time-steps. Also, note how the change in simulation time-step changes
the simulation results.
2.5. POSTLAB ANDLAB REPORT
Questions:
1. Find the analytical solution of the capacitor voltage as function of time, R, C, and
DC
V .
What is the time constant of the system? What is the value of the time constant in each of
the two cases (1a) and (1b)?
2. For the case (1a), determine the analytical solution of the capacitor voltage at time t = 3
seconds. What is the error between the analytical and numerical solutions at time t = 3
seconds? Give two reasons for the error.
3. Plot both the analytical solution and the simulation solution you obtained during the lab
and compare using Matlab for each of the cases (1a), (1b), (2a) and (2b). Do the analytical
time constant values agree with the values observed from your simulated data? In which
case(s) did the simulation not work well? Can you explain why?
Lab 2 report requirements:
a) Detailed solutions to the above three questions.
b) Hard copy of your commented sin(x) series approximation program.
c) Submit a commented copy of your sorting program.
d) Hard copy of your commented capacitor simulation program.
e) Turn in the debugging results required in section 2.2.4.
f) MATLAB plot of the capacitor voltage versus time for the two different values of R and C
used in the lab.