How to write a C program Yu-Chen, Shu Reference • B. W. Kernighan, D. M. Ritchie, The C Programming Language, 2nd ed. Prentice-Hall, 1988. • Website: http://libai.math.ncu.edu.tw/bcc16/C/C/ • This document: http://scicomp.math.ntu.edu.tw/~scc/asiaa/lecture_c.ppt Human VS Machine • Because computer only knows zero and one. If we want the computer help us doing something, we should talk to him in his way. What? I don’t speak Chinese 給我 關機!! C: intermediary language Compiler shutdown(now) 00101001010010010……… I am Mr. Chinese. I know Machine Language and C language. You can tell me in C. 給我 關機!! Our aim today • • • • Write some simple baby C programs. Compile them with gnu C compiler. Execute it. And see the result. How to translate algorithm to C program. A first example: hello.c #include <stdio.h> /* My first C program */ main() { printf(“Hello, world\n”); } • Use any text editor (notepad, winedt, vi, pico) to write/save this file. I suggest not to use “Microsoft WORD” Header (.h file) #include <stdio.h> /* My first C program */ main() { printf(“Hello, world\n”); } • At the first few lines in C program, we should include the header file. • The use of header file is like a dictionary. For example, the function “printf” is defined in stdio.h • When we write a C program, for those functions we want to use, we should include their header files. function and argument #include <stdio.h> /* My first C program */ main() { printf(“Hello, world\n”); } • main and printf are functions. • main function is what we want to do during the program. • printf is a function which print the argument: “Hello, world\n” to screen. Compiler PROMPT:> gcc hello.c PROMPT:> a.exe Hello world PROMPT:> • “Compile” means to translate the human language “C” into machine language(0 and 1). • At the command line: gcc hello.c • There are many compilers, such as intel c compiler(icc), gnu c compiler(gcc), turbo c compiler, … Executable file • If you use “gcc”, the default executable file is “a.out”(in unix system) or “a.exe”(in windows system). • At the command line, type a.out you will see the result. Conclusion • • • • • • Edit a file, xxx.c Include the header files we need. Write our ideas in main function. Compile it with compiler. Run the result :D Yes. It’s the framework of “How to write a C-program”. To Be Continued… How to write our idea • • • • Define variables. Look for algorithm. Write statement. Write some function we need. Our idea • We want to print out 50 geometric sequences. The first one is 1 and the common ratio is 0.5 . • Algorithm: an+1 = an x 0.5 . • How to translate it to C? Our thought • I need print out something.( include stdio.h ) • I need a variable for geometric sequence. • I need a index number which let me know the order of sequence. • I must tell C about the algorithm. Define variables #include <stdio.h> main() { int i; double a; a = 1; for(i=1;i<=50;++i) { printf("%.15f\n", a); a = a * 0.5; } } • In C program, there are many types of variables: – int : 4 bytes integer. Represent the integer from -231 to 231. – double : 8 bytes. A number which has floating decimal point. We shall talk about it at next class. • In this program, “i” is a integer variable and “a” is a double variable. Vector/Matrix • If we want to define a lot of “double” variables: v0, v1, v2, …, v9. We may write: double v[10]; • If we want a int variables: v00, v01, v02, v10, v11, v12. We may write: int v[2][3]; • Remember that the sub index of C is start from 0. (Fortran has a simple declaration.) User define variable • If you want a “account” variable include character variable name, and a double variable money, you should define as following in the first few line of the C program. typedef struct { char name[15]; double money; } account; • And then you can declare the account variable in C program: account shu; • Then access the name and money variables by printf(“%s”, shu.name); shu.money = 1e15; Statement #include <stdio.h> main() { int i; double a; a = 1; for(i=1;i<=50;++i) { printf("%.15f\n", a); a = a * 0.5; } } • A complete statement is ended with semicolon (;). – Example 1: int i; (It tells C that I want a integer naming “i”) – Example 2: a = 1; (It tells C that I want the variable “a” to be 1.) – Example 3: a=a*0.5; (It tells C that I want the value of “a” replaced by “a * 0.5”.) Assignment operator = • = , assign the value from right to left. – a = 1; means assign 1 to the variable a. – a = a*0.5; means assign a*0.5 to the variable a. • There are many assignment expression such as += *= -= – For example: the following two statements are identical. a = a*0.5; a *= 0.5; for structure #include <stdio.h> main() { int i; double a; a = 1; for(i=1;i<=50;++i) { printf("%.15f\n", a); a = a * 0.5; } } • If we want to do something for a fixed times. We should put it in “for structure” between a left brace and right brace. Here is a new word: “++i” The statement is equal to i = i + 1 You may write: “i++” Althought there are a little difference between “++i”, “i++”, and “i = i + 1”. I stop here because we don’t want to introduce increase-operator today. for structure • for (initial statement; loop criterion; steps statement) { The thing we want to do; } • The structure will start with initial statement, check the loop criterion, and do the steps statement after the thing we want to do. • For example the following for structure will print 1 to 50 to the screen. for(i=1; i <= 50; ++i) { printf(“%d\n”,i); } Equivalent statement 1 #include <stdio.h> main() { int i; double a; a = 1; for(i=1;i<=50;++i) { printf("%.15f\n", a); a = a * 0.5; } } They are the same. #include <stdio.h> main() { int i; double a; a = 1; i = 1; while(i<=50) { printf("%.15f\n", a); a = a * 0.5; i = i + 1; } } while structure while (loop criterion) { The thing we want to do; } • This structure only check the loop criterion. Equivalent statement 2 #include <stdio.h> main() { int i; double a; a = 1; for(i=1;i<=50;++i) { printf("%.15f\n", a); a = a * 0.5; } } They are the same. #include <stdio.h> main() { int i; double a; The loop criterion a = 1; “1” means the loop i = 1; while(1) will not stop. { printf("%.15f\n", a); a = a * 0.5; i = i + 1; if(i > 50) { break; } } } Here is a new word: “break”. It tells the loop structure will stop here. if structure if (criterion) { Something you want to do; } else { Another thing you want to do; } • “if structure” will check the criterion and then work only once on the blue block if the criterion is true, otherwise it will work on the green block only once. Compare operator • • • • • • Equal : == Greater : >, less : < Greater or equal: >=, less or equal : <= Not equal : != and : && or : || Some remarks • How to define our variables – We often define variables by their purpose, meanings, or symbols. For example, we often define a “double” variable rho for density. • Indentation – Make the program more readable. Reserved word • Reserved words are those words defined by C and they have specific meanings. For example: – int, char, float : define variables – for, while : loop structure – if, else : judgement • Reserved words can not be a variables or function name. Define a new function • If the function is not defined in C and we will use it very often in our work. For example, we need a function sinc(x) to return the value of sin(x)/x function example #include <math.h> double sinc(double x) { if(fabs(x)<1e-10) { return 1.0; } else { return sin(x)/x; } } • • • Because we need sine function, we must include <math.h> There are some new words in this code: – “fabs” means the absolute value of x. – “1e-10” means the scientific notation 1x10-10 . – “return” means that this function will return to the location calling this function by the value behind it. The programer should consider all cases. So when |x| is too small, we should return the value 1.0. function structure Type of function double sinc(double x) { if(fabs(x)<1e-10) { return 1.0; } else { return sin(x)/x; } } The input of the function. function name we will use in C program. Input/Output • • • • • scanf: read values from screen. printf: print values to screen. fopen: open a file. fscanf: read values from file. fprintf: print values to file. printf/scanf format • “%d” : means a integer. • “%f”, “%lf” : means a float decimal. • printf(“a = %f\n”, a); will print the value of a to screen. • scanf (“%f\n”, &a); will get the input from screen. The storage in memory • When we declare a “double” variable x, C locate a memory for x and put the memory information in &x. If we want to change the value of x, we need to provide the memory information of x. Here is the memory location of x Memory Block Memory Block &x x Here is the value of x The pointer double x; double *m; x = 1; m = &x; printf(“%f\n”,m[0]); It will print the value of x. • A powerful variable type in C; • “double *m;” means that m is a memory information. • Then m[k] is the value at the memony location m + k. Conclusion • We learn – Loop structure : for, while – Judgment structure: if – How to write a new function Newton method • Aim: solve the root of f(x) = 0 • Require: A function f, initial guess x0. • Algorithm: while |f(xn)| > 0 xn+1 = xn – f(xn)/f’(xn) Return the value xn. If f(xn)=0 Newton method #include <stdio.h> #include <math.h> double newton_method(double); double f(double); double df(double); int main() { double x; printf(“Initial x:”); scanf(“%lf”,&x); x = newton_method(x); printf(“The root is:%f\n”,x); } Here we declare the functions we want to use. We provide the memory information of x double newton_method(double x) { while(fabs(f(x)) > 1e-10) { x = x – f(x)/df(x); printf(“x : %f\n”, x); } return x; } double f(double x) { return x*x – x – 2; } double df(double x) { return 2*x-1; } Conservation laws int main() { define variables; initial(all variables we should define their value at first); while(t < final_time) { dt = find_dt(all variables related to time steps); update(the variables we should update); t = t + dt; } printf(“Yes. We did it!\n”); } We will talk about the algorithm next Monday.
© Copyright 2024