c tutorial - newcastle university...first example (using gcc) • example: ex_p1_1.c• read...
TRANSCRIPT
C Tutorial
Dr. Alex Bystrov
Newcastle University
School of Engineering
Induction week
Files, links
• See http://www.staff.ncl.ac.uk/a.bystrov/c_tutorial
• Uses the book ”C: How to Program” by Deitel
Why C?
• Small (32 keywords)
• Stable
• Existing code base
• Fast
• Low-level
Terminology
• Source code: (*.c) contain algorithms we are writing
• Header files: (*.h) interface to libraries
• Library: Collection of functions for specific tasks
• Compiler: translates source code to an executable
First Example (Using GCC)• Example: ex_p1_1.c
• Read c_tutorial.txt for the detailed instructions
• Create a directory ~/c_tutorial
• Inside this directory, create a file ex01.c using notepad++
• Type the code segment above
• Compile using: gcc ex01.c -o ex01
• Run the program:
• Don’t expect much as it does nothing !
main(){ }
1234
Example “Hello World!”
#include <stdio.h>
int main () { printf ("Hello world!\n");}
Third Example
• Example: ex_p1_3.c
1 2 3 4 5 6 7 8 91011121314
#include <stdio.h>
int main(void){
//Print somethingprintf("Hello World !\n");
//Require keyboard inputprintf("[Press any key to continue]\n");getchar();
//Exit to operating systemreturn 0;
}
Standard C Library
• Total of 24 libraries: (< > indicates system library)
• A few commonly used libraries:
• #include <math.h>
• #include <stdio.h>
• #include <stdlib.h>
• #include <time.h>
• #include <string.h>
Standard C Library (2)
• For other libraries:
Library is in current folder: #include "csp.h"
Library is in specific folder (Win): #include "H:\C_Tutorial\csp.h"
Library is in specific folder (Linux): #include "/home/ct/C_Tutorial/csp.h"
Comments• Single-line comments: //...
• Multi-line comments: /*... */
• Example: ex_p1_4.c
#include<stdio.h>/* This program prints hello world but also demonstrates the use of comments to add code explanations */int main(void){
// printf is included in stdio.hprintf("Hello World !\n");
//Require keyboard inputprintf("[Press any key to continue]\n");getchar();
return 0;}
1 2 3 4 5 6 7 8 910111213141516
Variable Types
Qualifiers Modifiers Specifiers
char
int
float
double
void
const
volatile
short
long
signed
unsigned
Integer, Decimal Data Types
Memory Range Data Type 8 bit 0...255 unsigned char
16(32) bit 0...216(32)−1 unsigned int
32(64) bit 0...232(64)−1 unsigned long
8 bit −128...+127 signed char, char
16(32) bit −215(31)...+215(31)-1 signed int, int
32(64) bit −231(63)...+231(63)-1 long, long int
32 bit 1.17E-38...3.40E+38 float
64(128)bit 2.22E-308...1.79E+308 double
Variables and Constants
• All variables and constants should be declared first: ex_p1_5.c
// Global variables#define N 64 //integer constant #define PI 3.141592654 //floating point constantconst float pi = 3.141592654;#define SCALE (float) 1/32768 //derived constantfloat sample; //single precision floating pointdouble x = 0.0; //double precision floating pointint n; // signed integerunsigned count = 0; // unsigned integer, initialised
void main(void){
//local variablesint k, n;...
}
1 2 3 4 5 6 7 8 910111213141516
Flow Control: if statement
• if syntax:
int m = 0, n = 0;... if (n > 10) n = 0;
if (n < 10){ n++; m--;}
1 2 3 4 5 6 7 8 910
Flow Control: if, else• if-else syntax:
int m = 0, n = 0;... if (n > 10){ n = 0; m = 0;}else { n++; m++;}
1 2 3 4 5 6 7 8 9101112
Flow Control: if, else if, else
• if, else if, else syntax:
int m = 0, n = 0;...if (m < 0) //Condition { n--; //n = n-1}else if (m > 0){ n++; //n = n+1}else{ n = 0;}
1 2 3 4 5 6 7 8 91011121314
Flow Control: Relational
• Relational less than/less than or equal to: <, <=
• Relational greater than/greater than or equal to: >, >=float x = 0.0, y = 0.0, z = 0.0;… //Code that modifies x,y,z valuesif (x >= y){ ... //Do something}else if (x <= z){ ... //Do something else}else... //Otherwise do this else
1 2 3 4 5 6 7 8 9101112
Flow Control: Logical
• Logical EQUAL: ==
• Logical NOT: !=
int n; ... //Code that modifies the value of n if (n != 0) { ... //Do something }
1 2 3 4 5 6
int n; ... //Code that modifies the value of n if (n == 0) { ... //Do something }
1 2 3 4 5 6
Flow Control: Logical (2)
• Logical AND: &&
• Logical OR: | |
float x = 0.0, y = 0.0, z = 0.0;... //Code that modifies x,y,z valuesif ((x < y) && (y < z)){ ... //Do something}
float x = 0.0, y = 0.0, z = 0.0;... //Code that modifies x,y,z valuesif ((x >= y) || (y <= z)){ ... //Do something}
1 2 3 4 5 6
1 2 3 4 5 6
Flow Control: case
unsigned day; ...//Code that modifies the value of dayswitch (day){ case 1: case 2: case 4: case 5: printf("Study hard\n"); break; case 3: printf("Study until 12:00am, go to gym\n"); break; case 6: case 7: printf("Relax\n"); break; default: printf("Study hard\n"); break; }
1 2 3 4 5 6 7 8 91011121314151617181920
I/O Functions: printf (1)
char ch = 'x';float pi=3.141592654;int m = 10; ...printf("The value of ch = %c \n", ch);printf("The value of pi = %f \n", pi);printf("The value of m = %d \n", m);
1 2 3 4 5 6 7
I/O Functions: printf (2)
• Placeholder anatomy: %[Modifier][Width][.Precision]Type
Spec Type Example%c char 'x'%d dec signed int -10%u dec unsigned int 131072%hu unsigned short int 2%f float, double 3.14 %e %E float exp. notation 3.14e0 or 3.14E0%x %X hex integer 0xff, 0xDEADBEEF%o octal integer 377%s string “hello!”
I/O Functions: printf (3)
Modifier Description0 Pads the conversion on the left with zeroesnumber Pads the conversion on the left with spaces (right alignment)- The conversion is left aligned within the display width+ Forces to display a sign (+ or -)space Adds a space in front of positive numbers
Review Exercise 1
• Write a small program to compute the following:
• Solutions:
-0.5000, 0.3827, 1.0472, 1.0039
• Hint: include the <math.h> header and compile using:
gcc revex1.c -o revex1 -lm
cos(2π
3) ,sin( π
8) ,cos−1
(0.5), tan−1( π
2)
Review Exercise 2
• Write a small program to compute the roots of a
quadratic polynomial: ax2 + bx + c = 0
• Algorithm:Compute the discriminant
If D is positive, there are two real-valued roots:
If D is zero, there is a double real-valued root:
If D is negative, there are two complex-valued roots:
D=b2−4a c
x1=−b+√D
2a, x2=
−b−√D2a
x1=x2=−b2a
x1=−b2a
+ j √−D2a
, x2=−b2a
− j √−D2a
Review Exercise 2 (cont.)
• Hint: For the complex solution split it up into real and imaginary parts.
• Test your program with:
a = 2, b = −3 and c = 1.a = 1, b = −6 and c = 9.a = 2, b = −3 and c = 5.
Loops: for
• Example: ex_p2_1.c
• Compile using: gcc ex_p2_1.c -o ex_p2_1 -lmRun using: ./ex_p2_1 > data.txt
int n, N = 100;float fc = 1000.0; //Carrier frequency in Hzfloat fs = 48000.0; //Sampling frequencyfloat t, Ts, wc, xc;
Ts = 1.0 / fs; //Sampling timewc = 2.0 * M_PI * fc; //Generate cosine signalfor (n = 0; n < N; n++){
t = n * Ts;xc = cos(wc * t);printf("%+.7f, %+.7f\n", t, xc);
}
1 2 3 4 5 6 7 8 9101112131415
Loops: while
• Example: ex_p2_2.c int n = 0, N = 100;float fc = 1000.0; //Carrier frequency in Hzfloat fs = 48000.0; //Sampling frequencyfloat t, Ts, wc, xc;
Ts = 1.0 / fs; //Sampling timewc = 2.0 * M_PI * fc;
//Generate cosine signalwhile(n < N){
t = n * Ts;xc = cos(wc * t);printf("%+.7f, %+.7f\n", t, xc);n++;
}
1 2 3 4 5 6 7 8 910111213141516
Loops: do
• Example: ex_p2_3.c
int n = 0, N = 100;float fc = 1000.0; //Carrier frequency in Hzfloat fs = 48000.0; //Sampling frequencyfloat t, Ts, wc, xc;
Ts = 1.0 / fs; //Sampling timewc = 2.0 * M_PI * fc;
//Generate cosine signaldo{
t = n * Ts;xc = cos(wc * t);printf("%+.7f, %+.7f\n", t, xc);
}while(++n < N);
1 2 3 4 5 6 7 8 910111213141516
Structures: struct
• Definition 1:
• Example: ex_p2_4.c
struct cmplx x;
x.real = 1.0;x.imag = 1.0;printf("x = %+.3f %+.3f * j\n", x.real, x.imag);
1 2 3 4 5
1 2 3 4 5
struct cmplx{ float real; float imag;}
Structures: struct, typedef
• Definition 2:
• Example: ex_p2_4.c
cmplx x;
x.real = 1.0;x.imag = 1.0;printf("x = %+.3f %+.3f * j\n", x.real, x.imag);
1 2 3 4 5
1 2 3 4 5
typedef struct{ float real; float imag;} cmplx;
Arrays (1)
• Definitions: ex_p2_6.c
• Array index limits for an array with N elements:
Lower index limit: 0Upper index limit: N-1
float x[1000];float y[] = {1.0, 1.0, 1.0};float z[1000] = {0.0};int adc[1024];char text[] = "C is cool!";
1 2 3 4 5
Arrays (2)
• Example: ex_p2_7.c
int n, N = 100;float fc = 1000.0; //Carrier frequency in Hzfloat fs = 48000.0; //Sampling frequencyfloat t, Ts, wc, xc[N];
Ts = 1.0 / fs; //Sampling timewc = 2.0 * M_PI * fc;
//Generate cosine signalfor (n = 0; n < N; n++){
t = n * Ts;xc[n] = cosf(wc * t);printf("%+.7f, %+.7f\n", t, xc[n]);
}
1 2 3 4 5 6 7 8 9101112131415
Two Dimensional Arrays
• Example: ex_p2_8.c
float X[3][3];float Y[3][3]={{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}};int m, n;
for (m = 0; m < 3; m++){
for (n = 0; n < 3; n++) printf("%f ",X[m][n] = 2.0 * Y[m][n]);printf("\n");
}
1 2 3 4 5 6 7 8 9101112
Functions (1)
• Definition: ex_p2_9.c
typedef struct{
float real;float imag;float mag;
} cmplx;
float mag(cmplx x){
float y;y = sqrtf(x.real*x.real+x.imag*x.imag);
return y; }
1 2 3 4 5 6 7 8 91011121314
Functions (2)
• Example: ex_p2_9.c
cmplx y;
y.real = 1.0;y.imag = 1.0;
y.mag = mag(y);printf("The magnitude of %+.3f %+.3f * j is %f\n", y.real, y.imag, y.mag);
1 2 3 4 5 6 7 8
Functions (3)
• Functions with array input variables: ex_p2_10.c
• Example: ex_p2_10.cint n, N = 4;float z[4] = {1.2, 1.1, 0.9, 0.9}, average;
printf("The mean of z is %f\n", mean(z,N));
float mean(float x[], unsigned long N){
int n;float avg = 0.0;
for (n = 0; n < N; n++)avg += x[n];
return avg / ((float)N);}
1 2 3 4 5 6 7 8 910
1 2 3 4
Functions (4)
• Functions using global variables: ex_p2_11.c
// x[] and N are global variables (above the main function)float mean(){
int n;float avg = 0;
for (n = 0; n < N; n++)avg += x[n];
return avg / ((float)N);
}
1 2 3 4 5 6 7 8 9101112
Pointers (1)
• A pointer is a variable that points to (references)a memory location where data is stored.
• Pointer declarations examples: ex_p2_12.c
float *p1, *p2;int *p3;
1 2
0 1 2 3 4 5 6 7 8 9 10 …..
9
Computer memory
Pointers (2)
• Address operator: &
int y = 5;int *yPtr;
yPtr = &y; // yPtr gets address of y // yPtr “points to” y
1 2 3 4 5
yPtr y
51000
location 800 location 1000
Pointers and Arrays
• Example: ex_p2_13.c
float *p1 = NULL, x[5] = {0.1, 0.2, 0.3, 0.4, 0.5}, y1, y2;p1 = &x[0]; // point p1 to the first element of x[]y1 = *(p1+3); // Equivalent to y1 = x[3]y2 = p1[3]; // Equivalent to y2 = x[3]
printf("y1 = %f\n", y1);printf("y2 = %f\n", y2);
1 2 3 4 5 6 7
Bitwise Operators (1)
Type Range SymbolLogical Operators bitwise complement ~ bitwise AND & bitwise OR | bitwise XOR ^
Shift Operators left shift << right shift >>
Bitwise Operators (2)
• Example 1: ex_p2_14.c
• Example 2: ex_p2_15.cunsigned short int a = 1, b = 5;
//Bitwise operationsprintf("~a = %hu\n", ~a);printf("a & b = %u\n", a&b);printf("a | b = %u\n", a|b);printf("a ^ b = %u\n", a^b);
unsigned int a = 0, b = 3;
//Left/right shiftprintf("a=%u\n", a);a = b << 2;printf("a=%u\n", a);a >>= 1;printf("a=%u\n", a);
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
Review Exercise 3
• Write a program that generates into an arraya linear frequency modulated chirp as follows:Start frequency: f0 = 1 kHzStop frequency: f1 = 2 kHzSampling frequency: fs = 48 kHzDuration: Td = 50 msThe chirp formula is given as:
• Plot the generated signal in Matlab
• Use both for, while, as well as the do approaches
y (t)=cos [2π(f 0 t+f 1−f 0
2T dt 2)]
Review Exercise 4
• Extend the structure for the complex numbers toinclude the phase argument of a complex number. Write a function, cphi, that computes phase argumentof a complex number.
• Write 4 functions that implement addition, subtraction, multiplication and division for complex numbers with names cadd, csub, cmul, and cdiv. Test the functions for z1=-1+j and z2=2j.