0% found this document useful (0 votes)
62 views

Course of Computational Physics 1: Chapter 1: Programming in C

This document summarizes Lecture 2 of Chapter 1 from the Computational Physics 1 course. The lecture covers looping constructs in C like for, while, and do-while loops. It also discusses symbolic constants, character input/output, counting characters, arrays, functions, and writing a function to fetch a line of input. Examples are provided for each topic to demonstrate how to implement it in C code.

Uploaded by

hoangdt8
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Course of Computational Physics 1: Chapter 1: Programming in C

This document summarizes Lecture 2 of Chapter 1 from the Computational Physics 1 course. The lecture covers looping constructs in C like for, while, and do-while loops. It also discusses symbolic constants, character input/output, counting characters, arrays, functions, and writing a function to fetch a line of input. Examples are provided for each topic to demonstrate how to implement it in C code.

Uploaded by

hoangdt8
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.

Course of Computational Physics 1 Chapter 1: Programming in C Lecture 2: Introduction to C (2)


Dr Sonnet H. Q. Nguyen Hanoi University of Science

Lecture Outline 1. Aims and Objectives 2. Looping Constructs 3. Symbolic Constants 4. Character Input and Output 5. Examples: Counting Characters 6. Arrays 7. Functions 8. Simple Examples of Functions 9. Call by Value and by Reference 10. Example of Function: A function to fetch a line of input 11. Exercises

Aims and Objectives


For, while and do-while loop

Symbolic Constants Character Input and Output Logical AND (&&) and OR (||) Arrays Functions Exercises

Looping for
for (initialisation ; condition ; expression) { statements; }

Sonnet H. Q. Nguyen, Hanoi University of Science Page 1/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


The initialisation step occurs before the loop is entered for the first time. The condition is checked before the body of the loop is executed. The expression step is executed every time the body is executed.

The temperature conversion program with a for loop.


// program name: temp1.c #include <stdio.h> main() { int fahr; for (fahr=0; fahr <= 300; fahr = fahr+20) { printf("%3d %6.1f\n",fahr,(5.0/9.0)*(fahr-32)); } }

Notice that the calculation is part of the printf statement - wherever you can use a variable of a certain type (i.e., the calculation returns a value of type float, and is displayed as a floating point number) you can use a function or an expression.

Looping while The while loop in C/C++ is very similar to the for loop. The for statement contains two semicolons, which allows placement of the initialization statement, the negation of the termination condition and the iterative statement in it. However, the while loop allows placement of only the condition so the other two statements must be placed outside the while statement.
while ( conditional ) { statements ; }

while the conditional is true, perform statements. If there is only one statement, the braces can be omitted.

Example:

Sonnet H. Q. Nguyen, Hanoi University of Science Page 2/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


#include <stdio.h> int main(void) { int j; j = -5; while(j <= 0) { printf("%d ", j); j = j + 1; } return 0;

} Example: The temperature conversion program with a while loop instead of a for loop.
#include <stdio.h> main() { float fahr, celcius; int lower, upper, step; lower = 0; // lower limit of temp table upper = 300; //upper limit step = 20; // stepsize printf("Fahrenheit\tCelsius\n"); fahr=lower; while(fahr<=upper) { celcius = (5.0/9.0) * (fahr-32); printf("%f\t%f\n", fahr, celcius); fahr = fahr + step; } }

Looping do - while
do { statements; } while (conditional)

The conditional is checked after the body of the loop is executed while the conditional is true, the loop continues (i.e. execute statements inside the loop); otherwise it ends the loop.

Example:
// a program to show the use of do-while #include <stdio.h> int main() { int j = -5; // initialization do {

Sonnet H. Q. Nguyen, Hanoi University of Science Page 3/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


printf("%d\n", j); j = j + 1; } while(j <= 0); return 0; } // conditional

Symbolic Constants

The numbers 0, 20, and 300 in the program mean very little to readers of the program unless they are very familiar with what the program is doing
for (fahr=0; fahr <= 300; fahr = fahr+20)

C allows the definition of symbolic constants - names that will be replaced with their values when the program is compiled Symbolic constants are defined before main(), and the syntax is
#define NAME value

Example
// program name: temp2.c #include <stdio.h> #define LOWER 0 /* lower limit of table */ #define UPPER 300 /* upper limit */ #define STEP 20 /* step size */ main() { int fahr; for (fahr=LOWER; fahr<=UPPER; fahr=fahr+STEP) { printf("%3d %6.1f\n",fahr,(5.0/9.0)*(fahr-32)); } }

Sonnet H. Q. Nguyen, Hanoi University of Science Page 4/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


There is no semi-colon after the definition of a symbolic constant You cannot change the value of a symbolic constant at run-time

Character Input and Output


C is a low Level Language As such, it can only manipulate data structures that are directly supported by the hardware (characters and numeric literals) C has a standard library of functions for applying more powerful, flexible and convenient data structures - but first we will see how C performs low-level character input and output, from the keyboard and to the computer screen The simplest I/O functions are
getchar(); /* get an input character */ putchar(); /* send an output character */

Although getchar() and putchar() appear to handle characters, they are actually manipulating the ASCII values for the characters. getchar() reads a char and converts it into ASCII, and putchar() converts an ASCII value into a char! A program to read input from the keyboard and send the input as output to the screen
//program name: readchar.c #include <stdio.h> main() { int c; /* store the next char input */ while ((c = getchar()) != EOF) { putchar(c); } }

Other standard functions gets, fgets, getch, getline, puts, fputs, putch, etc.

Counting Characters

Every character on the keyboard has an ASCII value Let's say that we want to count the number of characters, spaces, and newlines (returns) in the input Now a character is anything that is input. But how can we count spaces and newlines? Single quotes around a character tell C to use that character's ASCII value. The character ' ', therefore is the ASCII value for the space character (32), and is an integer. " " is a space, and is a character! How can we refer to newline? C supports the use of special characters to refer to some difficult-to-refer-to characters. These chars are a single letter representation and are escaped! newline = '\n', ASCII value 10. Sonnet H. Q. Nguyen, Hanoi University of Science Page 5/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


//program name: countAllChars.c #include <stdio.h> main() { int c; /* for input char */ int nc, ns, nl; /* declare vars */ nc = ns = nl = 0; /* init. vars to 0 */ while ((c = getchar()) != EOF) { ++nc; if (c == ' ') ++ns; else if (c == '\n') ++nl; } printf("nc=%d; ns=%d; nl=%d", nc,ns,nl); }

Another Program

In more complicated conditionals you might want to test for multiple conditions, e.g., if the char is a space or if it is a newline, then... Let's rewrite the previous program so that we will not keep a count of newlines and spaces...
//program name: countChars.c #include <stdio.h> main() { int c; int nc = 0; /* declare vars */ while ((c = getchar()) != EOF) { if (! (c == ' ' || c == '\n')) ++nc; } printf("nc=%d", nc); }

Arrays
float a[4]={1.9,2.8,5,4.1}; float a[]={1.2,4.5,3,9.1,8}; int b[][3]={{1,2,3},{3,2,4}}; int c[3][2]={{1,2},{3,4},{5,6}}; char d[]=I dont like C; sizeof(a); sizeof(data-type);

Building a complex data type, based on character input First, a vector or uni-dimensional array Declare it as type int, float, char, etc, depending on what each cell can contain Sonnet H. Q. Nguyen, Hanoi University of Science Page 6/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.

Write a program to count the occurrence of letters in the range a - z and A - Z. Ignore other chars.
//program name: countAlpha.c #include <stdio.h> main() { int c; /* store input char */ int nletters[26]; /*array of 26 cells */ int i; /* handy variable */ for (i = 0; i < 26; ++i) nletters[i] = 0; while ((c = getchar()) != EOF) { if (c >= 'a' && c <= 'z') ++nletters[c - 'a']; else if (c >= 'A' && c <= 'Z') ++nletters[c - 'A']; } for (i = 0; i < 26; ++i) { c = 'a' + i; putchar(c); printf(" = %d\n", nletters[i]); } } Output for input: aAbcBc a = 2 b = 2 c = 2

Functions

A function is a subroutine or a procedure - a self-contained program that can be referenced (called) by other programs and functions. Below we propose one simple function and the way to call it.
//program name: swap.c void swap(float x, float y); /* function swap */ { float z; z=x; x=y; y=z; } main() { /* main program */ float x=3.1; float y=2.5; swap(x,y); printf(\n x= %0.1f y= %0.1f,x,y); }

Sonnet H. Q. Nguyen, Hanoi University of Science Page 7/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.

In the example below, we propose a function power(x,n) computing xn where x,n are integers.
//program name: power.c #include <stdio.h> int power(int base, int n); /* prototype */ main() { int i; /* handy variable */ for (i = 0; i <= 10; ++i) printf("3^%d %d\n",i,power(3,i)); } int power(int base, int i) { int n; /*handy variable */ for (n = 1; i > 0; --i) n = n * base; return n; }

Call by Value

Variables in the function are local to the function. You can use the same variables as in the calling procedure, without overwriting the original values!

Call by Reference

To change the value of the original variable.

A function to fetch a line of input


Reading a character at a time is no great shakes. Usually want to manipulate data at a higher level than character. Typically, want to read input as complete `lines' (e.g., records). Let's say that the record delimiter is the newline character. C stores character strings as a character array. The special character '\0' is used to indicate the end of the string (even after '\n'!).
//program name: readLine.c #include <stdio.h> #define MAX 80 /* max line length */ int getline(char line[],int max); /*prototype*/ main() { char s[MAX]; getline(s, MAX);

Sonnet H. Q. Nguyen, Hanoi University of Science Page 8/9

Computational Physics 1, Chapter 1: Introduction to C programming, Lecture 2.


printf("%s", s); } int getline(char s[], int max) { int c, i; /*store an input char, index*/ for(i=0; i< max && (c=getchar()) != '\n' && c != EOF; s[i++]=c); if (c == '\n') s[i++] = '\n'; s[i] = '\0'; return i; }

Exercises 1. Write a program for finding the maximum and minimum of four numbers (fload) read from the keyboard. After that, the program will ask an user whether s/he wants to continue. If the answer is Y (read from the keyboard) then it continues, if the answer is N, then it stops, otherwise it waits until the answer is either Y or N. 2. Write a similar program to sort five numbers into a non-decreasing sequence. For example: if the input is {2.9, 1.2, 9.3, 0.7, 5.5}, then the output will be {0.7, 1.2, 2.9, 5.5, 9.3}. 3. Write a function (and the main program) for solving quadratic equation: ax2+bx+c=0 where a,b,c are float. 4. Write a program to read an integer (n<105) from the keyboard, check whether it is a prime number, and print out the conclusion. 5. Write a function/program to read two integers (n,m<106) from the keyboard and print out their greatest common divisor gcd(n,m).

Sonnet H. Q. Nguyen, Hanoi University of Science Page 9/9

You might also like