lab2
DESCRIPTION
Lab documentTRANSCRIPT
![Page 1: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/1.jpg)
LAB 2C PROGRAMMING TECHNIQUES
2.1. LAB OBJECTIVE
Lab 2 objectives include the following
More C programming techniquesProgramming with loops (for loop, while loop etc.)Use of arraysThe use of functionsPerforming 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 tothe following concepts
if statement for loopswhile 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 likegetch */
void main(){
char a=’a’;
while(a != 'q') {a = getch();printf("You typed in %c\n", a);
}
![Page 2: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/2.jpg)
}
/* 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 passthrough the loop.
For example, consider a program that prompts a user for an input and calculates the squareroot 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 dope’s 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 ofsmaller, self contained components each of which has some unique purpose. This is called amodular programming approach. There are several advantages to this approach including
![Page 3: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/3.jpg)
repeated access to a group of instructions
a different set of data can be transferred to the function each time it is accessedmore logical and clear programsone 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 greaterof 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 moredetails on functions.
#include <stdio.h>
/* max returns the maximum of two values */float max(float a, float b) {
if (a>b)return(a);
elsereturn(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(“\nThegreater 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 withDeveloper Studio. You will learn how to single step through a program and observe the valuesof variables at different program execution stages. This can be an invaluable tool in debuggingyour 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 postlabreport.
#include <stdio.h>main(){
int num1 = 5, num2 = 10;int* pnum = NULL;
![Page 4: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/4.jpg)
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 infiniteseries
sin(x) = x – x3/3! + x5/5! – x7/7! + …
where x is expressed in radians (Note: radians = 180o).
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 theresult from the series equals the result from the sin(x) library function up to the 6th
decimal place.
b) For a value of x = 1.3, how many terms do you need for achieving the sameaccuracy as in (a)?
Assume that there exists a function double fact(int n) that returns the factorial value of aninteger 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 includemath.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 C tutorial contains an example program that uses while loops.
3. Write a program to solve the RC-circuit shown below.
![Page 5: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/5.jpg)
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 DCV =
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, Vc, and DCV .
2) Approximate the differential equation with a finite difference equation. Use thefirst order forward difference equation
stepsize
(i)V1)(iV
dt
dV ccc
to approximate the derivative. Numerically solve the above difference equation forVc(i+1).
3) Write a C program that iterates the difference equation and prints out the voltageat 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.0002Fb) R = 5,000 ohms, C = 0.0001F
b) Use a simulation time step of 0.5 seconds. Use the following values of R and Ca) R = 10,000 ohms, C = 0.0002Fb) 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.
![Page 6: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/6.jpg)
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 filewill 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 namedatafile.
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 thedata in array variable called Vc. You can use this variable for plotting the capacitor voltagewith respect to time. For plotting, create an array of time values beginning from 0 to 5 secondsin 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 AND LAB REPORT
Questions:
1. Find the analytical solution of the capacitor voltage as function of time, R, C, and DCV .
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
![Page 7: Lab2](https://reader031.vdocuments.us/reader031/viewer/2022011720/577cc6681a28aba7119e223d/html5/thumbnails/7.jpg)
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.