A Quick guide to C. Dr Alun Moon September 16, Contents. Introduction 2 Unix 2 On Program design 4. C programming Good practice 4

Size: px
Start display at page:

Download "A Quick guide to C. Dr Alun Moon September 16, Contents. Introduction 2 Unix 2 On Program design 4. C programming Good practice 4"

Transcription

1 A Quick guide to C Dr Alun Moon September 16, 2014 Contents Introduction 2 Unix 2 On Program design 4 a few simple steps 4 C programming Good practice 4 File contents 4 Rob Pike rules 5 Philosopy of good programs 5 Program structure 6 External Structure 6 Internal structure 7 Processing 7 Compiling and running 8 Anatomy of a C program 8 C language 10 Variables and declaration 10 Declaration 10 Constants 10 Arithmetic expressions 11 Control flow 11 Logical values 11 Language elements 11 Arrays, Strings and pointers 13 Arrays 13 Strings 13 Arrays of strings 14 Pointers 14 Functions 15 Changing parameters using pointers 16 Using functions in separate files 16

2 a quick guide to c 2 Output and Input 17 Fields 18 Input 19 Command line 19 Standard input 20 Reading input line by line 21 File handling 21 Errors 22 Examples 23 sum 23 wordstat 24 man pages 25 Introduction C 1 is a powerful language originally developed by Dennis Ritchie for writing the Unix operating system. The examples here are shown running on a Unix system, though ports of C exist for Macs 2 and Windows. Editors A C program is just text. Any good text editor will do, emacs, vi, gedit,... 1 Brian Kerngihan and Denis Ritche. The C Programming Language. Prentice Hall, second edition, 1988; and Stephen Kochan. Programming in C. Samms, third edition, OSX is of course a Unix system (derrived from BSD) Unix C programs are written to run under Unix. any text editor, vi, emacs, gedit, scite, etc. will do. gcc is a command line tool that combines the functions of compiler assembler linker the files likely to be encountered are C source C header object executable Tools assembler converts assembly code into object files compiler converts c-code into object filrs

3 a quick guide to c 3 linker combines object files together debugger controls running of the program to allow execution of single instructions and examine contents of variables Conventions for file extensions There are a number of commonly used file extensions used in C and assembly programming. Most of these are common to all systems. The various tools assume these extensions are used..s assembler Contains assembly language instructions.c C source Contains the source code for the programme in the C programming language.h C header Contains function and variable declarations along with relevant constants.o object Contains information about the location and contents of memory

4 a quick guide to c 4 On Program design Programming is both an art and a science. It is an art in the sense of a master craftsman. In this guide I hope to introduce the thinking behind programming. It is aimed at those needing to program in C, but the skills of a programmer are independent of the language used. Remember, programming cannot be learnt by simply reading a book. It has to be learnt through practice writing programs! Take the time to practice, write your own solutions to the problems here and the exercises given. Look at my solutions, but they will be different to yours, after all I ve been doing this a lot longer. Take the time to read through and learn from my solutions. But don t forget to write your own. a few simple steps Identifying features in the program. Is the first step taking the problem into the design. It is the process of identifying what the essential functions of the program are to be. Just as important is identifying what is not needed. Breaking the problem down into smaller pieces. Most problems can be broken down into smaller pieces. Either as distinct sub-programs or as a series of tasks within a program, or even function. This functional decomposition allows a complex task to be reduced to smaller simpler pieces that fit together to perform the task. Identifying functions and writing the prototype. Once the tasks have been found, often they can be written down as the names of functions to use. With the name goes the information that the function needs and the values it returns. Writing the program logic. Once the functions are known, what they do can be transfered into the program logic. The logic for a function can be very simple or complex depending on the task. C programming Good practice File contents Program source files are simply text files. They can be worked on by any editor All an IDE does is wrap up an editor and the invocation of the tools in a single front-end. the linker control file is another text file

5 a quick guide to c 5 Corollary 1 Since source files are text, they can be created and edited by other programs. Corollary 2 (Treat programs as documents) express concepts with clarity readability comment when code is not clear reference them Rob Pike rules Rob pike wrote some rules for C 3 3 Rob Pike. Notes on programming in C URL 1. You can t tell where a program is going to spend its time. Bottlenecks occur in surprising places, so don t try to second guess and put in a speed hack until you ve proven where the bottleneck is. 2. Measure. Don t tune for speed until you ve measured, and even then don t unless one part of the code overwhelms the rest. 3. Fancy algorithms are slow when n is small, and n is usually small. Fancy algorithms have big constants. Until you know then n is frequently going to be big, don t get fancy. (Even if n does get big, use Rule 2 first.) 4. Fancy algorithms are buggier than simple ones, and they re much harder to implement. Use simple algorithms as well as simple data structures. 5. Data dominates. If you ve chosen the right data structures and organised things well, the algroithms will always be self-evident. Data structures, not algorithms, are central to programming. se/c/pikestyle.html Rob Pike was one of the team who developed Unix for which C was invented Philosopy of good programs From The Art of Unix Programming 4 1. Rule of Modularity: Write simple parts connected by clean interfaces. 2. Rule of Clarity: Clarity is better than cleverness. 4 Eric S. Raymond. The Art of Unix Programming. Professional Computing. Addison-Wesley, 1 edition, URL html/ 3. Rule of Composition: Design programs to be connected to other programs. 4. Rule Rule of Separation: Separate policy from mechanism; separate interfaces from engines. 5. Rule of Simplicity: Design for simplicity; add complexity only where you must.

6 a quick guide to c 6 6. Rule of Parsimony: Write a big program only when it is clear by demonstration that nothing else will do. 7. Rule of Transparency: Design for visibility to make inspection and debugging easier. 8. Rule of Robustness: Robustness is the child of transparency and simplicity. 9. Rule of Representation: Fold knowledge into data so program logic can be stupid and robust. 10. Rule of Least Surprise: In interface design, always do the least surprising thing. 11. Rule of Silence: When a program has nothing surprising to say, it should say nothing. 12. Rule of Repair: When you must fail, fail noisily and as soon as possible. 13. Rule of Economy: Programmer time is expensive; conserve it in preference to machine time. 14. Rule of Generation: Avoid hand-hacking; write programs to write programs when you can. 15. Rule of Optimization: Prototype before polishing. Get it working before you optimize it. 16. Rule of Diversity: Distrust all claims for one true way. 17. Rule of Extensibility: Design for the future, because it will be here sooner than you think. Program structure There are a number of repeated patterns that occur in programs. These are both how the program interacts with the outside world and the internal structure of the program. Understanding how these patterns work and applying them to the implemetation of probles is the key to effective programming. External Structure Input and output The first layer of patterns is how the program interacts with the outside world. Most programs can be thought of as a filter, transforming input into output. input Program output

7 a quick guide to c 7 Cooperating programs Programs can be designed to act together, the output from one becomes the input to the next. The actual mechanism is handled by the outside environment. input Program a Program b output Corollary 3 The upshot of this is that the formats of the input and output data are important in designing a program. Corollary 4 Design programs to cooperate. Corollary 5 Sometimes a problem can be split into separate cooperating programs. Internal structure There are two basic patterns that are useful at this stage for thinking about the internal structure of a program. These can apply at any level Most programs have the same basic internal structure. 1. initialise the program. Set up data structures, parameters and constants. 2. process perform the operations of the program. 3. finish clean up after the program. initialise process finish This pattern applies at any scale, the program as a whole, a function, a loop within a block of code. Processing The processing performed by the program follows a similar pattern 1. read some data 2. process the data 3. write the results. Usually there is some loop wrapped around this pattern. Depending on the problem the processing can occur for each item read, or all the data needs to be read before the processing can occur.

8 a quick guide to c 8 read process write Compiling and running Consider the following program saved in the file hello.c hello.c main() printf("hello, world\n"); The C compiler is gcc, it produces an executable file that can be used as a Unix command. By default the file is called a.out, as shown below alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ The -o switch can be used to set the name of the output file alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ Anatomy of a C program Looking at the hello, world program above and the example below, several features of C can be seen.

9 a quick guide to c 9 /* A program to print out the arguments to main. It illustrates how the command line input is split into words, and assigned to the argc and argv parameters to main. */ int main (int argc, char *argv[]) int i; for (i = 0; i <= argc; ++i) printf ("argument %i=%s\n", i, argv[i]); #include both programs start with a #include statement. This is similar to the role of the import statement in Java. It makes declarations of functions available to the program. The file ending in.h is often called a header file. There are two forms for quoting the filename, which determines where the file is looked for. 1. Angle brackets <name> looks first in system directories for standard header files 2. Double quotes "name" looks in the current directory first. main both programs have a main function which is the program entry point. Java has the static public void main method. Unlike java there are three forms. 1. main() is the simplest. No command-line arguments are passed to the function. Although no return type is given an int is assumed. I wouldn t recomment this form as not giving a return type is not good practice. 2. int main() is the same as the first, but with an explicit return type. 3. int main(int argc, char *argv[]) is the third form. The command-line is split into words (using spaces) and the words placed in argv, while argc has the number of words. For more details see. statements end with a semicolon. declarations of variables are the same as in Java. The type name, followed by the variable name, then an optional initial value. block structure C has a block structure for function bodies, loop and conditional (if statement) bodies. A block is a series of statements enclosed within braces and. In the case of a loop or

10 a quick guide to c 10 if statement if the block has a single statement, then the enclosing braces can be omitted. There is some debate as to whether it is good style to use braces or not for a single statement block, it may be better to always use braces for consistency, as in. for(i=0 ; i<=argc ; ++i) printf("argument %i=%s\n", i, argv[i]); comments begin with a /* and end with a */ C language In some respects you will find C similar to Java. Which is not surprising as the syntax of Java was inspired by C. Variables and declaration The basic data types in C are char single byte, capable of holding one character int an integer, typically reflecting the natural size of integers on the host machine In addition integer variables (char and int) can be declared as signed or unsigned. Signed variables use the same number of bits as unsigned variables, but the signed ones use two s-complement arithmetic. The big difference between types in C and Java is the number of bits used. In Java an int is always 32bits, whereas in C an int is whatever a word of memory is (at least 16 bits). There are also floating point numbers for non-integer arithmetic. Declaration Declaring variables occurs the same way as in Java, the type is followed by a variable name. Names are case-sensitive in C. int width, length, height; float initialprice = 45.2f; char tab = \t ; Constants Constant values for each of the basic data types can be written according to the following table. char a \n \x3f etc int 1234 float 123.4f 4.34e4f note the f suffix double e4

11 a quick guide to c 11 Arithmetic expressions Arithmetic expressions in C are much the same as in Java. The only difference is that in Java exceptions can be throws for errors such as divide-by-zero, in C the program will crash and die. All the arithmetic and logical operators from Java are available in C. The type of the result depends on the types of the operands, the result has the broadest type of the operands where int is promoted to float and float to double as needed. The modulus operator % only acts on integer types. Be careful when using division; with integer types integer division is performed (5/2 = 2), whereas with one or more floats floating point division is performed (5.0/2 = 2.5). Control flow C has the usual control flow supported by Java, if, switch, for and while. Logical values C has no boolean type as Java does. The following convention is used to interpret integer values zero false not zero true The usual comparison and logical operators are provided (<=, ==, && etc). Language elements if The if statement has the form if ( expression ) statement block If the expression is non-zero the statement block is executed. if... else The if... else statement has the form if (expression) statement block 1 else statement block 2 If the expression is non-zero the first statement block is executed, if zero the second is executed. if... else if... If statements can be used as the second block creating a multi-way choice. if ( expression 1 ) statement block 1 else if ( expression 2 ) statement block 2

12 a quick guide to c 12 else if ( expression 3 ) statement block 3 else if ( expression 4 ) statement block 4 else statement block 5 switch As in Java the switch statement allows a multi-way test. The value tested must be an integer or char, as must be the values in each case. The break keyword is needed to exit the switch, without it all the subsequent statements in the switch will be executed until the switch exits. switch (c) case n : statements break; case t : statements break; case f : statements break; default: statements for The for loop is the same as in Java, except that the loop variable must be declared outside the for loop. for( initial value ; continuation condition ; increment ) statement block while The while loop is identical and behaves the same way as the while loop in Java. This is often used is reading a file. /* read and process input line-by-line */ const int LINEBUFFER = 80; /* define a length of a line buffer */ char line[linebufer]; /* declare a buffer to read lines into */ main() while( fgets(stdin, LINEBUFFER, line) ) /* process line */

13 a quick guide to c 13 Arrays, Strings and pointers Arrays, strings and pointers are all related in C. Arrays are declared and used as in Java. Once created array sizes cannot be changed. Unlike Java there are no checks used on the array index to see if it is within an array. Once an array has been created, there is no way to find its length using a.length attribute as in Java. Arrays The following example fills an array with squares of numbers and then prints them out in reverse order. main() const int LISTSIZE = 10; int squares[listsize]; int i; for( i=0 ; i<listsize ; ++i) squares[i] = i*i; for( i=listsize-1 ; i>=0 ; --i ) printf("%2d squared is %3d\n",i,squares[i]); Arrays can be initialised in the declaration, in these cases the size is given implicitly in the data. char int daysinmonth[] = 31,28,31,30,31,30,31,31,30,31,30,31; This allocates space for 12 integers, and fills the array with the given values. Strings C has no string data type or class. Strings are represented as arrays of char. Strings are stored as a series of ASCII codes in the char array, the end of the string is marked by a zero byte \0. So for a given length of string, an array needs one more space to store the zero byte. The following declarations establish strings. char buffer[1024]; char message[] = "hello, world\n"; char *greeting = "salutations"; The first form allocates 1024 bytes of uninitialised space. The second allocates 14 bytes, the 13 in the string literal and the ter-

14 a quick guide to c 14 minating zero byte. The last form allocates 12 bytes, the 11 in the word and the zero terminating byte. Strings cannot be manipulated as in Java or C++. The <strings.h> library provides several functions that are of use. strlen calculate the length of a string strcat concatenate two strings strcpy copy a string Beware: when using the strcpy and strcat functions, the destination array must have enough space allocated. There is no protection against overflowing the space into random memory. Not checking data to avoid these kinds of overflows is the main cause of vulnerabilities to attacks by viruses, worms and similar hostile programs. There are versions of copy and concatenate that have length checks, strncpy and strncat. These specify the maximum number of characters to copy. Arrays of strings Arrays of strings are simply arrays of pointers to char. The following three declarations are equivalent. char days[][]; char *months[]; char **years; The difference is how the sizes are allocated. All forms can be subsequently be used in similar ways. An array of strings can be initialised as follows. char **daysofweek = "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ; One common use of an array of strings is the arguments passed to main. Pointers Pointers are variables that refer to the location data is stored at. Given a variable a, the ampersand operator get the location of a, the star operator gets the value the pointer points to.

15 a quick guide to c 15 main() int a = 5; int b = 2; int c; int *p; /* a pointer to an int */ printf("a = %i, b = %i, c = %i\n",a,b,c); p = &a; /* p points to a */ c = *p; /* c now equals a */ *p = b; /* a now equals b */ printf("a = %i, b = %i, c = %i\n",a,b,c); Pointers have their main uses in functions and input (see below). NULL pointers. many system functions return pointers. Usually if the function cannot complete its operation, then a pointer with the NULL value is returned (defined in several header files). Functions Functions in C are equivalent to methods in Java. Because C is not object oriented, there is no public or private qualifier. A function is declared with a return type, a name, and a parameter list. int square(int x) return x*x; Defines a function called square that takes a single integer argument, and returns the square (x 2 ) of the value. The parameters passed to a function can be changed in the function, but this is not reflected in the variable outside the functions. int cube(int x) x = x*x*x; return x; Returns the cube of a number. If it is called as follows, int n=3; cube(n);

16 a quick guide to c 16 returns the cube of n, but the value of n is unchanged in the calling program. Function parameters are said to be passed by value. The parameter given in the function call is evaluated and the resulting value copied into the variable declared in the function definition. Changing parameters using pointers If the value of a parameter needs to be changed, this can be done by using a pointer as a parameter. For example if the value of an integer needs to be halved this can be done as follows. void halve(int *n) *n /= 2; remember: a /= 2 is equivalent to a = a/2 To call the function you can only use a variable 5 and must pass the address of the variable. As follows: 5 Not an expession int n = 4; halve(&n); Using functions in separate files The program can be split into several files. Often related functions are collected into a single library. In order to use a function, it needs to be declared before it can be used. int max(int a, int b); /* declaration of max */ main() int p = 5; int q = 8; printf("%i\n", max(p,q) ); int max(int a, int b) /* definition of max */ return (a>=b)?a:b; The max function can be put into a separate file, which we will call libmax.c. The convention is to have a header file sharing the base-name containing the declarations.

17 a quick guide to c 17 libmax.c int max(int a, int b) /* definition of max */ return (a>=b)?a:b; libmax.h int max(int a, int b); /* declaration of max */ The function is then used by including the header file in the program where it is used and compiling the two files. #include "libmax.h" main() int p = 5; int q = 8; printf("%i\n", max(p,q) ); The two can be compiled together simply by passing both filenames to the compiler. alun@debian:~$ gcc -o usemax usemax.c libmax.c alun@debian:~$ usemax 8 alun@debian:~$ The library can be compiled separately. The compiler -c option is used, it creates an object file with the same base-name and a.o extension. The object file can then be used in a separate use of the compiler with the main program. alun@debian:~$ gcc -c libmax.c alun@debian:~$ gcc libmax.o usemax.c -o usemax alun@debian:~$ usemax 8 alun@debian:~$ Output and Input The IO library in C is stdio, to use it include the system header file. The basic output function is printf. It prints the string supplied

18 a quick guide to c 18 to the function on stdout, note that the newline has to be given explicitly in the string using the \n sequence. Fields printf can format and print numbers and text. The place for the value is introduced by a % sign, the type of the variable to be printed is given by a letter as follows i integer f floating point s string (char array) The general format of the placeholder is % width. precision type where the width is the minimum number of characters to use, precision is the number of decimal places to use, and type is a letter as above. For example the program, int main() int n=5; printf(" %d \n",n); printf(" %5d \n",n); printf(" %05d \n",n); printf(" %-5d \n",n); float p= 1.0/6.0; printf(" %f \n",p); printf(" %6f \n",p); printf(" %6.2f \n",p); printf(" %-6.2f \n",p); produces For strings the precision is the maximum number of characters to use from the string.

19 a quick guide to c 19 main() char *sample = "This is a bit of sample text!"; printf(" %s \n",sample); printf(" %10s \n",sample); printf(" %40s \n",sample); printf(" %-40s \n",sample); printf(" %20.10s \n",sample); printf(" %.10s \n",sample); produces This is a bit of sample text! This is a bit of sample text! This is a bit of sample text! This is a bit of sample text! This is a This is a Input There are two ways of getting input into your program, commandline arguments, and the stdio library. The command line arguments are quick and easy, useful for giving initial data to the program. The stdio functions are more flexible. Command line The command line is passed into the program via arguments to main, an example program and its output are shown below. /* A program to print out the arguments to main. It illustrates how the command line input is split into words, and assigned to the argc and argv parameters to main. */ int main (int argc, char *argv[]) int i; for (i = 0; i <= argc; ++i) printf ("argument %i=%s\n", i, argv[i]);

20 a quick guide to c 20 alun@debian:~$ cmd this is a sample line argument 0=cmd argument 1=this argument 2=is argument 3=a argument 4=sample argument 5=line argument 6=(null) alun@debian:~$ The first parameter to main receives the number of words in the command-line. The input is split into words using spaces as separators. The second parameter is an array of strings (pointers to characters). The first element is the name of the program, the array has a null pointer after the last command-line argument. Standard input The basic input function in stdio is scanf. It uses the same strings to indicate data to be read. The width and precision are interpreted differently. The major difference between input and output is that pointers to variables are needed in order to store the values read. For variables such as integers remember to use the ampersand, scanf("%i",&a) where a is an integer int a. For strings the array name is also a pointer, so the ampersand is not needed scanf("%s",name), where name is a string char name[8]. Remember to allocate space for a string to be read into! Type letters The same letters are used to indicate the type of data being read as printf d integer i integer f floating point s string (non-whitespace) The string type will read as many non-whitespace characters as possible. The d type reads an integer. The i type also reads an integer, but will cope with hexadecimal numbers that start with 0x (0xABCD) and octal values that start with a 0 (0777). The rest of the format string works as follows. Any whitespace characters match any amount of whitespace in the input. Nonwhitespace characters are expected to match the next exact character in the input. For example scanf("from: %s",addr) will match and read the senders address in a message, but not match the subject line. Because of the way whitespace is read, output formated with the string "%5d %5d" can be read with the string " %d %d".

21 a quick guide to c 21 Reading input line by line The scanf family of functions do not recognise the end of a line, successive calls to scanf keep reading input reading across lines if needed. A safe way to read a file line by line is to use the fgets function. It is recommended to use fgets as the maximum number of characters to be read can be given, avoiding buffer overflows. The following is a template to read a file, one line at a time. enum BUFFERSIZE = 132; /* makes a constant integer */ char buffer[buffersize]; /* buffer to read lines into */ main() while( fgets(buffer, BUFFERSIZE, stdin) ) /* process line here... */ The line can then be processed using sscanf a variant of scanf that reads from a string rather than input. sscanf(buffer, "%s %s", name, class); reads two strings (name and class) from the string buffer (from above), separated by whitespace. Of course this will not cope where the name has any spaces. fred jones M8 will be read as the name being fred the class being jones. Getting round this limitation of scanf is part of the art of designing C programs and the data structures used for files File handling So far all the functions have operated on standard input and standard output. One trivial way of reading or writing to files is to use shell redirection alun@debian:~$ classes < data > results alun@debian:~$ runs the program classes reading from the file data instead of standard input and writing to the file results instead of standard output. The standard IO library provides a number of types and functions to support reading and writing files. File handles: are used to manage files. Pointers to these are returned by the fopen function and passed to the other functions. fopen returns a file handle pointer. It takes two parameters, a filename string and a mode string. Some of the mode strings 6 are 6 try man 3 fopen for more details

22 a quick guide to c 22 r open for reading w open for writing, setting the length to zero and deleting any existing contents overwrites a file w+ As for w but creates the file if if does not exist. a Open for appending, output is added to the end of the file. fopen returns either a valid file-handle or NULL if some error has occurred. The return value should always be tested. fclose is used to close a file once it has been finished with. Programs should always clean up after themselves by closing open file-handles. fprintf writes data to the file. A pointer to file-handle supplied by fopen is passed as the first parameter, the second is a printf format string, the remaining parameters are the data for the format string as in printf. fscanf reads from an open file. The first parameter is a pointer to a file handle, the rest are as for scanf. Errors Occasionally errors may occur, such as an attempt to open a non existent file for reading. Depending on the function different values are returned to indicate an error. Read the man page for the function to find out what return value indicates an error, and test for it. Often the variable errno (from errno.h) is set to indicate the kind of error. Test the return value for the function 7 not errno. A function perror prints a specified message to standard-error along with the corresponding error-message for errno. Rather than using return, there is an exit function (in stdlib.h) that causes the program to exit and causes some default cleanup. It also defines two constants EXIT_SUCCESS and EXIT_FAILURE to indicate the success of the program. 7 if in doubt check the man pages

23 a quick guide to c 23 Examples sum The following example reads a column of numbers from a file and prints the sum at the bottom of the file. #include <stdlib.h> #include <errno.h> #include <strings.h> int main( int argc, char **argv ) enum BUFSIZE=132; char line[bufsize]; FILE *data; int d, total=0; if (argc<2) exit(exit_failure); /* no filename given, return a failure exit code*/ data = fopen(argv[1],"r"); if( data == NULL ) perror("sum cannot open a file"); exit(exit_failure); while( fgets(line, BUFSIZE, data) ) sscanf(line,"%i",&d); total+=d; fclose(data); /* a more compact file open */ if(!(data=fopen(argv[1],"a")) ) perror("can t open file for appending"); exit(exit_failure); fprintf(data," \n%8d\n",total); fclose(data);

24 a quick guide to c 24 wordstat The following example reads a series of words 8. It counts the words read and maintains a record of the longest word read. 8 remember a word is a nonwhitespace sequence of characters #include <stdlib.h> #include <strings.h> #include <errno.h> int main( int argc, char **argv) enum WORDBUFERSIZE=80; char word[wordbufersize]; FILE *data; int words=0, maxlen=0; if(argc<2) exit(exit_failure); if (!(data = fopen(argv[1],"r")) ) perror("wordstat can t open a file"); exit(exit_failure); while( fscanf(data,"%s",word)!=eof ) if (strlen(word)>maxlen) maxlen=strlen(word); ++words; printf("%d words, max length %d characters\n",words, maxlen); fclose(data);

25 a quick guide to c 25 man pages All the C functions are documented in section 3 of the Unix Programmers Manual. To read the page for printf use; alun@debian:~$ man 3 printf alun@debian:~$ References Brian Kerngihan and Denis Ritche. The C Programming Language. Prentice Hall, second edition, Stephen Kochan. Programming in C. Samms, third edition, Rob Pike. Notes on programming in C URL lysator.liu.se/c/pikestyle.html. Eric S. Raymond. The Art of Unix Programming. Professional Computing. Addison-Wesley, 1 edition, URL org/esr/writings/taoup/html/.

C Programming. A quick introduction for embedded systems. Dr. Alun Moon UNN/CEIS. September 2008

C Programming. A quick introduction for embedded systems. Dr. Alun Moon UNN/CEIS. September 2008 C Programming A quick introduction for embedded systems Dr. Alun Moon UNN/CEIS September 2008 Dr. Alun Moon (UNN/CEIS) C Programming September 2008 1 / 13 Programming is both an art and a science. It is

More information

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1 A Quick guide to C for Networks and Operating Systems

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html UQC146S1 Introductory Image Processing in C Ian Johnson Room 3P16 Telephone: extension 3167 Email: Ian.Johnson@uwe.ac.uk http://www.csm.uwe.ac.uk/ ~irjohnson/uqc146s1.html Ian Johnson 1 UQC146S1 What is

More information

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable. CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,

More information

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: C and Unix Overview This course is about computer organization, but since most of our programming is

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering Arrays, Strings, & Pointers Arrays, Strings, & Pointers are

More information

CS 261 Fall Mike Lam, Professor. Structs and I/O

CS 261 Fall Mike Lam, Professor. Structs and I/O CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 7: Introduction to C (pronobis@kth.se) Overview Overview Lecture 7: Introduction to C Wrap Up Basic Datatypes and printf Branching and Loops in C Constant values Wrap Up Lecture 7: Introduction

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

8. Characters, Strings and Files

8. Characters, Strings and Files REGZ9280: Global Education Short Course - Engineering 8. Characters, Strings and Files Reading: Moffat, Chapter 7, 11 REGZ9280 14s2 8. Characters and Arrays 1 ASCII The ASCII table gives a correspondence

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

File Handling in C. EECS 2031 Fall October 27, 2014

File Handling in C. EECS 2031 Fall October 27, 2014 File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically

More information

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview Computer Science 322 Operating Systems Mount Holyoke College Spring 2010 Topic Notes: C and Unix Overview This course is about operating systems, but since most of our upcoming programming is in C on a

More information

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static

More information

Preview from Notesale.co.uk Page 6 of 52

Preview from Notesale.co.uk Page 6 of 52 Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (yaseminb@kth.se) Overview Overview Roots of C Getting started with C Closer look at Hello World Programming Environment Discussion Basic Datatypes and printf Schedule Introduction to C - main part of

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1 F28HS2 Hardware-Software Interface Lecture 1: Programming in C 1 Introduction in this half of the course we will study: system level programming in C assembly language programming for the ARM processor

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO Input and Output Streams and Stream IO 1 Standard Input and Output Need: #include Large list of input and output functions to: Read and write from a stream Open a file and make a stream Close

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

C mini reference. 5 Binary numbers 12

C mini reference. 5 Binary numbers 12 C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

ch = argv[i][++j]; /* why does ++j but j++ does not? */

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

just a ((somewhat) safer) dialect.

just a ((somewhat) safer) dialect. Intro_to_C Page 1 Intro to C Tuesday, September 07, 2004 5:30 PM C was developed specifically for writing operating systems Low level of abstraction. "Just above machine language." Direct access to the

More information

CS Programming In C

CS Programming In C CS 24000 - Programming In C Week Two: Basic C Program Organization and Data Types Zhiyuan Li Department of Computer Science Purdue University, USA 2 int main() { } return 0; The Simplest C Program C programs

More information

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Tutorial 1 C Tutorial: Pointers, Strings, Exec TCSS 422: Operating Systems Institute of Technology Spring 2017 University of Washington Tacoma http://faculty.washington.edu/wlloyd/courses/tcss422 Tutorial 1 C Tutorial: Pointers, Strings, Exec The purpose

More information

Programming in C and C++

Programming in C and C++ Programming in C and C++ 1. Types Variables Expressions & Statements Dr. Anil Madhavapeddy University of Cambridge (based on previous years thanks to Alan Mycroft, Alastair Beresford and Andrew Moore)

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify

More information

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays Strings and Pointers Announcements Lab 4 Why are you taking this course? Lab 5 #, 8: Reading in data from file using fscanf Quiz Quiz Strings Special character arrays End in null character, \ char hi[6];

More information

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Basic C Programming Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island Announcements Exam 1 (20%): Feb. 27 (Tuesday) Tentative Proposal Deadline:

More information

SWEN-250 Personal SE. Introduction to C

SWEN-250 Personal SE. Introduction to C SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

C Introduction. Comparison w/ Java, Memory Model, and Pointers

C Introduction. Comparison w/ Java, Memory Model, and Pointers CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language

More information

Structure of this course. C and C++ Past Exam Questions. Text books

Structure of this course. C and C++ Past Exam Questions. Text books Structure of this course C and C++ 1. Types Variables Expressions & Statements Alastair R. Beresford University of Cambridge Lent Term 2008 Programming in C: types, variables, expressions & statements

More information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C. Reading. goto Considered Harmful History Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program

More information

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7 CS 220: Introduction to Parallel Computing Input/Output Lecture 7 Input/Output Most useful programs will provide some type of input or output Thus far, we ve prompted the user to enter their input directly

More information

Programming in C. What is C?... What is C?

Programming in C. What is C?... What is C? C Programming in C UVic SEng 265 Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier, in 1969, Ritchie and Thompson developed the Unix operating system We will be focusing on a version

More information

Programming in C UVic SEng 265

Programming in C UVic SEng 265 Programming in C UVic SEng 265 Daniel M. German Department of Computer Science University of Victoria 1 SEng 265 dmgerman@uvic.ca C Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier,

More information

CS1100 Introduction to Programming

CS1100 Introduction to Programming CS1100 Introduction to Programming Arrays Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB, PSK, NSN, DK, TAG CS&E, IIT M 1 An Array

More information

COMP s1 Lecture 1

COMP s1 Lecture 1 COMP1511 18s1 Lecture 1 1 Numbers In, Numbers Out Andrew Bennett more printf variables scanf 2 Before we begin introduce yourself to the person sitting next to you why did

More information

Programming in C. What is C?... What is C?

Programming in C. What is C?... What is C? Programming in C UVic SEng 265 C Developed by Brian Kernighan and Dennis Ritchie of Bell Labs Earlier, in 1969, Ritchie and Thompson developed the Unix operating system We will be focusing on a version

More information

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

IO = Input & Output 2

IO = Input & Output 2 Input & Output 1 IO = Input & Output 2 Idioms 3 Input and output in C are simple, in theory, because everything is handled by function calls, and you just have to look up the documentation of each function

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

File IO and command line input CSE 2451

File IO and command line input CSE 2451 File IO and command line input CSE 2451 File functions Open/Close files fopen() open a stream for a file fclose() closes a stream One character at a time: fgetc() similar to getchar() fputc() similar to

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

EMBEDDED SYSTEMS PROGRAMMING Language Basics

EMBEDDED SYSTEMS PROGRAMMING Language Basics EMBEDDED SYSTEMS PROGRAMMING 2014-15 Language Basics (PROGRAMMING) LANGUAGES "The tower of Babel" by Pieter Bruegel the Elder Kunsthistorisches Museum, Vienna ABOUT THE LANGUAGES C (1972) Designed to replace

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23 Structure of this course Programming in C: types, variables, expressions & statements functions, compilation, pre-processor pointers, structures extended examples, tick hints n tips Programming in C++:

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection Overview By the end of the lab, you will be able to: declare variables perform basic arithmetic operations on integer variables

More information

C Libraries. Bart Childs Complementary to the text(s)

C Libraries. Bart Childs Complementary to the text(s) C Libraries Bart Childs Complementary to the text(s) 2006 C was designed to make extensive use of a number of libraries. A great reference for student purposes is appendix B of the K&R book. This list

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

G52CPP C++ Programming Lecture 3. Dr Jason Atkin G52CPP C++ Programming Lecture 3 Dr Jason Atkin E-Mail: jaa@cs.nott.ac.uk 1 Revision so far C/C++ designed for speed, Java for catching errors Java hides a lot of the details (so can C++) Much of C, C++

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

Warm-up sheet: Programming in C

Warm-up sheet: Programming in C Warm-up sheet: Programming in C Programming for Embedded Systems Uppsala University January 20, 2015 Introduction Here are some basic exercises in the programming language C. Hopefully you already have

More information

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO Input and Output Streams and Stream IO 1 Standard Input and Output Need: #include Large list of input and output functions to: Read and write from a stream Open a file and make a stream Close

More information

COMP1917: 09 Arrays and Strings

COMP1917: 09 Arrays and Strings COMP1917: 09 Arrays and Strings Sim Mautner s.mautner@unsw.edu.au August 15, 2016 Sim Mautner (UNSW) COMP1917: 09 Arrays and Strings August 15, 2016 1 / 14 Arrays int sum(int n1, int n2); int sum(int n1,

More information

Programming in C and C++

Programming in C and C++ Programming in C and C++ Types, Variables, Expressions and Statements Neel Krishnaswami and Alan Mycroft Course Structure Basics of C: Types, variables, expressions and statements Functions, compilation

More information

Introduction to C An overview of the programming language C, syntax, data types and input/output

Introduction to C An overview of the programming language C, syntax, data types and input/output Introduction to C An overview of the programming language C, syntax, data types and input/output Teil I. a first C program TU Bergakademie Freiberg INMO M. Brändel 2018-10-23 1 PROGRAMMING LANGUAGE C is

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead. Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection Overview By the end of the lab, you will be able to: declare variables perform basic arithmetic operations on integer variables

More information

Programmer s Points to Remember:

Programmer s Points to Remember: Programmer s Points to Remember: Always do bounds checking on arrays. Always do bounds checking on pointer arithmetic. Before you copy to, format, or send input to a buffer make sure it is big enough to

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Goals of C  The Goals of C (cont.)  Goals of this Lecture The Design of C: A Rational Reconstruction Goals of this Lecture The Design of C: A Rational Reconstruction Help you learn about: The decisions that were available to the designers of C The decisions that were made by the designers of C Why? Learning

More information

MPATE-GE 2618: C Programming for Music Technology. Syllabus

MPATE-GE 2618: C Programming for Music Technology. Syllabus MPATE-GE 2618: C Programming for Music Technology Instructor Dr. Schuyler Quackenbush schuyler.quackenbush@nyu.edu Lab Teaching Assistant TBD Description Syllabus MPATE-GE 2618: C Programming for Music

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

C for C++ Programmers

C for C++ Programmers C for C++ Programmers CS230/330 - Operating Systems (Winter 2001). The good news is that C syntax is almost identical to that of C++. However, there are many things you're used to that aren't available

More information

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008

Summary of Last Class. Processes. C vs. Java. C vs. Java (cont.) C vs. Java (cont.) Tevfik Ko!ar. CSC Systems Programming Fall 2008 CSC 4304 - Systems Programming Fall 2008 Lecture - II Basics of C Programming Summary of Last Class Basics of UNIX: logging in, changing password text editing with vi, emacs and pico file and director

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information