View
215
Download
1
Category
Preview:
Citation preview
1
Lab 1. C Introduction
C: – Developed by Bell lab. in 1972.
– a procedure-oriented programming language. Developing environments:
– Editing
– Preprocessing (header files)
– Compile (.obj)
– Link (.exe)
– load
– Execution Include:
– Head files used in the main file.
#include <stdlib.h>#include <stdio.h>#include <time.h>#include <math.h>
2
Variable and constant:– Must be declared before use
– e.g. int i=3; float f=15.7; double x.
– const int max=100; Data type transfer:
– Assignment: x=1;
– Mathematic operations: y=i/5+2/3;
– Model transfer: i=(int)(x+0.5);
– Function call: x=sum(a,b); Basic input/output commands:
printf(“\t xxxx %vf1 xxx %vf2 xxx \n”, var1, var2);
scanf(“\t %vf1 %vf2 ”, &var1, &var2);
Variable format
Address
3
Output format:
Mathematic operators: – Similar to those in Matlab
%: Remainder
4
Others: – int i=3;
– int a;
If/else:If (condition){ statements;}elseif (condition){ statements;}else{ }
If (condition){ statements;}else{ statements;}
5
Practice 1:– Input three numbers from the keyboard.
– Calculate the maximum, the minimum, and the average values.
– Print the result on the screen.
For loops:
for (initial setting; terminate conditions; index operations){ statements}
6
Array:
Function:– Call by value
– Call by reference
Elements of the array
Array name
Function name
Return value
7
Define (preprocessor):– Increase readability– Increase the flexibility for paramter changes– Replace simple function
8
Practice 2:– Input two sequences from the keyboard.
– Calculate the convolution of the sequences.
– Print the result on the screen.
File operations (read):
FILE * fp; //declare file pointerfp = fopen(“filename.dat","rb"); // rb: read for bitsfor (i=0 ; i<512 ; i++) {fread(&temp,1,4,fp); // 1: one byte, 4: 4x1 bytes at a time
x[i] = temp; // store the read value into an array}
* int/float: use 4 bytes to store one value
FILE * fp; fp = fopen(“filename.dat","rb"); fread(x,4,sizeof(x),fp);
Or,
9
File operation (write):
File operations in Matlab:
FILE * fp1; //declare file pointerfp = fopen(“filename.dat",“wb"); // wb: write for bitsfwrite(x,4,sizeof(x),fp1); // 4: 4 bytes a unit
r = randint(1,n); s = r > 0.5; fid = fopen(‘filename.dat','wb'); fwrite(fid, s,'ubit1'); % ubit1: unsigned bitfclose(fid); % float/int32
fid2 = fopen(‘filename.dat','rb','n'); Buffer = fread(fid2,n,'ubit1'); fclose(fid2);
10
Practice 3:– Store the values of inputted two sequences in two files.
– Read the values from the files.
– Calculate the convolution of the sequences.
– Store the result into another file.
Homework– Find out how to create a function with sequence input and s
equence output.
– Rewrite the convolution operations with a function.
– Generate two sequences with Matlab and store them in the two files.
– Use C to read the files and conduct convolution operations.
– Store the result to another file and use Matlab to read it.
Recommended