<<

CS210 - The University of Auckland

COMPSCI 210

C

Introduction to Programming in

C: a bit of history (1) y First generation computer languages: Machine code. ◦ Computer hardware is designed to understand and execute what is called “machine code” (instructions to tell the computer what to do). ◦ A computer program: the bit pattern of the machine code to be loaded into the computer memory. It could be specified manually, using switches on the front panel for the computer

y Second generation computer languages: Assembly language. ◦ Specifying a computer program as the bit pattern of the machine code was very consuming, and error prone. A human readable/writable form of machine code was developed, namely “assembly language”. ◦ Another program, called an assembler, was developed to take a textual version of the machine code, and translate it into machine code.

assembler

Translation from Assembly language to Machine code

1 CS210 - The University of Auckland

C: a bit of history (2) y Third generation computer languages: High level languages. ◦ Assembly language is very low level, and depends on the computer architecture. ◦ High level languages were developed, that were relatively machine independent, and like the notation of mathematics. (~1955) and Basic (~1964): still had to build control statements out of one line if statements and goto statements, and there were no recursive functions. ◦ Pascal (~1970) and C (~1972) were developed, with support for data structures. ◦ 1971, Ken Thompson developed a FORTRAN compiler, instead ended up developed a compiler for a new high-level language he called B. ◦ In 1972, Dennis Ritchie Bell Lab, built on B to create a new language called C (next to B) which inherited Thompson's syntax. Most of the components of were eventually rewritten in C. Because of its convenience and power, C went on to become the most popular programming language in the world over the next quarter century. ◦ Modern languages (third generation languages), such as C++ (~1983) and Java (~1995), are object orie nte la nguages (both are based on C). Third gene rat io n la nguages rep rese nt the main programming languages in use today.

From: http://phpimpact.files.wordpress.com/2008/06/program ming_languages.png

C: A HighHigh--LevelLevel Language

y Gives symbolic names to values ◦ don’t need to know which register or memory location ◦ e.g. ADD R1, R2, R3 vs X = Y + Z y Provides abstraction of underlying hardware ◦ operations do not depend on instruction set ◦ example: can “a = b * c”, even though LC-3 doesn’t have a multiply instruction y Provides expressiveness ◦ use meaningful symbols that convey meaning ◦ simple expressions for common control patterns (if-then- else, while, break,…) y Enhances code readability ◦ Up to the user to write clear code (e.g. comments, code structure)

2 CS210 - The University of Auckland

Compiling a C Program y Entire mechanism is usually called the “compiler” y Preprocessor ◦ macro substitution x Substitute symbolic names of constants by their values ◦ conditional compilation x Use pre-processor directives (starting with #) to define several compilation configuration by suppressing certain portion of codes ◦ “source-level” transformations x output is still C y Compiler ◦ generates object x machine instructions y Linker ◦ combine object files (including libraries) into executable image

Compiler

y Source Code Analysis ◦ “front end” ◦ parses programs to ididtifentify its pieces x variables, expressions, statements, functions, etc. ◦ depends on language (not on target machine) y Code Generation ◦ “back end” ◦ generates machine code from analyzed source ◦ may optimize machine code to it run more efficiently ◦ very dependent on target machine y Symbol Table ◦ map between symbolic names and items ◦ like assembler, but more kinds of information

3 CS210 - The University of Auckland

Example: HelloWorld.c Language Structure y Structure: ◦ C is a block structured programming language, consistingggppj of one or more files making up the project.

◦ Header File Section LEA R0, ; x It contains Preprocessor Directives PUTS LC3 code for .... ◦ Data Section (optional) MESG .STRINGZ "Hello World.\n" x It contains the #define statement to set up a constant ◦ Code Section Header files to /* The file HelloWorld program */ x It represents be included #include Data Section the actual high #define CONSTANT_NAME 4 -level instructions that you want the processor int main() { to execute: printf, scanf… printf("Hello World.\n"); Main C Program Section return 0; }

No semi-colon #include

Language Structure Before compiling, copy contents of stdio.h (standard input/output) y Header File Section (#include) into source code ◦ is a preprocessor statement (compiler directive) ◦ tells the compiler to "go get" the specified file (header file ). x is primarily a list of function, constants, and other definitions. x has a corresponding implementation file, contains function bodies. x correspond to parts of the C library. x A library is simply a package of code that someone else has written to make your life easier! Similar to API in Java x #include x includes the "standard I/O library" into your program. The standard I/O library lets you read input from the keyboard and write output to the screen. ◦ can also include your own multiple source code files x with angle brackets <> to tell the compiler that it only needs to look for the file in the standard include directory. x with double quotes “” to tell the compiler that it starts to search the file from the working directory #include “library.h”

4 CS210 - The University of Auckland

Language Structure y Data Section ◦ It contains the #define statement to set up a constant. ◦ Before compiling, replace all instances of the constant in the code with the value. ◦ It is highly recommended that if you have to use a constant value in your program that you define it in this section ◦ The syntax is No equal sign #define CONSTANT_NAME constant_value No semi-colon ◦ It is good programming practice that constant’s names should only contain CAPITAL LETTERS and the _ (underscore) character ◦ You can define integer, real or character constants #define INTEGER_CONSTANT 101 INTEGER_CONSTANT .FILL 101 #define REAL_CONSTANT 3.1427 #define CHARACTER_CONSTANT “hello” CHARACTER_CONSTANT .STRINGZ “hello" ◦ Later on in code body, REAL_CONSTANT will be replaced by 3.1427

LC3 code No float in LC3

int main() { printf("Hello World.\n"); Language Structure return 0; } y Code Section ◦ It represents the actual high-level instructions that you want the processor to execute. ◦ The main met ho d is the starti ng point of your program. Every C program must have the main method. ◦ The beginning and end of the main section are delimited by chain brackets - { and } ◦ The return statement causes the function to return an error code of 0 (no error) to the operating system. x Error code of 1 – with error ◦ It is good programming practice to indent your code in this section ◦ It is good practice to include comments in you C file x Comments can be placed either x Within the bounds of /* and */ (can span multiple lines) x On a single line starting with // Main function can also take int main(int argc, char **argv) arguments like in Java {...}

5 CS210 - The University of Auckland

Language Structure y Comments ◦ Begins with /* and ends with */ ◦ Can span multiple lines ◦ Cannot have a comment within a comment /* Comment out this routine Compile_error_with_comment.c for testing /* Open file */ Invalid comment if(c == 't') break; */ ◦ Comments are not recognized within a string x example: "my/*don't print this*/string" would be printed as: my/*don't print this*/string ◦ As before, use comments to help reader, not to confuse or to restate the obvious

Other C Compilers y Free C Compilers ◦ The URL http://www.thefreecountry.com/compilers/cpp.shtml provides information on manyyp free C compilers. y Cygwin ◦ Cygwin on a Windows system. x gives you a UNIX like system running on top of Windows, and includes the GNU C compiler, “gcc”. x Information on Cygwin -> tutorial y Bloodshed, ◦ provides a free C compiler, and is available from http://www.bloodshed.net/devcpp.html. y Visual Studio ◦ Download MS Visual C++ Express edition x http://www.microsoft.com/express/ ◦ A commercial version of Visual Studio can be obtained from the University web site, https://www.se.auckland.ac.nz/msdn/

6 CS210 - The University of Auckland

Some C compilers

From http://en.wikipedia.org/wiki/List_of_compilers

Compiling & Running

y Using Microsoft Visual ◦ Graphical interface + button controls for compiling ◦ The assignment will be run using the C compiler on Cygwin so you’d better recompile your cod e in UUinix bbfefore sub mitt ittded y Steps: ◦ Having c_code.c file handly somewhere ◦ Start Visual Studio ◦ Choose File >> New >> Project ◦ Then choose Visual C++ >> Win32 Consol Application and enter a project name ◦ Choose Application Settings >> Empty project then click Finish ◦ You then can drag and drop c_code.c file on to the project on left hand side ◦ Double click on file name to open and edit ◦ In order to compile it, click on Debug button

◦ Or press F5 ◦ Or Ctrl + F5 to compile, run and leave command window open ◦ Alternatively, you can use Visual Studio Command to compile using cl filename.c ◦ From Start >> Program files >> Visual Studio >> Visual Studio Tools >> VS command

7 CS210 - The University of Auckland

ES Represents LEA R0,String ; Input and Output \a Bell (alert) PUTS \b Backspace y Variety of I/O functions in C. \f Formfeed y Must include \n New line \ Carriage return printf("%s\n", String); \t Horizontal tab ◦ String contains characters to print and formatting directions \v Vertical tab for variables. \' Single quotation mark ◦ This call says to print the variable \" Double quotation mark counter as a decimal integer, \\ Backslash ollowed by a linefeed or new line (\n). %? Output scanf("%d", &startPoint); %c character ◦ String contains formatting directions for looking at input. %d Decimal integer ◦ This call says to read a decimal integer %f Floating point numbers and assign it to the variable %u Unsigned integer startPoint. %o Octal integer (Don't worry about the & yet.) %x integer

Sample_output.c More About Output y Syntax: ◦ To display a message, just put the message in double quotes. printf (format _ strin g [, one or more values ]); pp(rintf("Hello World." ); ◦ To display values you embed formats into the printf string. A format starts with “%” and conversion characters. After the string, you list the variables, constants or values that you want mapped to the formats in the format string. printf("\nExample: %c", x); y Conversion Characters

printf("\n%c %c %c", 'A', 'B', 'C');

printf("\n%d, Octal: %d, Hexadecimal: %d", x1, x2, x3); printf("\nx1=%d, x2(octal)=%o, x3(hexadecimal)=%x", x1, x2, x3);

printf("%d\n", startPoint - counter);

Can use 21, Octal: 17, Hexadecimal: 33 expression x1=21, x2(octal)=21, x3(hexadecimal)=21

8 CS210 - The University of Auckland

Sample_output.c More About Output y Conversion Character Modifiers: ◦ Insert a modifying number inside many of the numeric conversion characters. This number tells C how many print positions to use. x A width number inside a conversion character x C right-justifies the number in the width you specify. i.e. padding the number with leading blanks if the number does not fill the full width x A minus sign before the width specifier x C left-justifies the number inside the width. x The modifier (()%width.decimalsf) x to print a floating number with a specified number of decimal places to the right of the decimal point [flags][width][.[precision][ prefix]

printf("\n%d %d %d", 456, 456, 456); printf("\n%5d %5d %5d", 456, 456, 456); printf("\n%-5d %-5d %-5d", 456, 456, 456); printf("\n%f", 134.568767); printf("\n%6.2f", 134.568767);

02InputDemo.c More About Input y Scanf() function ◦ Allow the user to enter text on the keyboard until the user hits the key on the keyboard. ◦ The function then stores in a particular variable. In order to get the value back from scanf, the variable must be passed by reference. (Use “&”) ;Store input y Syntax: ;into VARIABLE ;Loop of LEA R5 VARIABLE GETC STR R1, R5, #0 ADD R1, R0, #0 Keyboard scanf(format description, &variable_name); ◦ This is a “” string containing ONLY one of the variable type descriptors (i.e. %d, %f, %c etc.) ◦ The type of variable indicated in the format description should always agree with the variable type which follows it scanf("%c", &nextChar);

scanf("%d", &number);

printf("\nEnter your temperature : "); Note: If the data type is double, scanf("%f",&temperature); change the tpe descriptor to “%lf”

9 CS210 - The University of Auckland

02InputDemo.c More About Input ◦ More Examples: scanf("%d %d", &a, &b); x Note: The blank between the two %d indicates that the two values entered will be separated by wh ite space (bl(blkank, tab or ) . x The user should type two numbers on the same line, separated by a space, then press the enter key. He could also use the enter key after each value entered. scanf("%d-%d-%d", &day, &month, &year); x Reads three integers separated by “-” x scanf() also return true or false if(scanf("%d", &n) == 1) printf("%d\n", n); x So this only print out a number if it’s in correct format x Input = 123 then 123 is print out x Input = abc then nothing is print out x Input = 123.123 then 123 is printout only x This can be used to check for correct input of type scanf("%50s", word) x Scan for string with maximum of 50 characters only

03ReadChar.c Single character Input & Output

y getChar and putChar ◦ getchar function can be used to read a character from the standard input device. ◦ putchar function can be used for writing characters one at a time to the output terminal.

printf ("\nEnter one character:") ; // message to user PUTC c = getchar () ; // get a char from keyboard and Stores variable C. printf ("\nThe character you typed is = %c", c); putchar(c); GETC

//endless loop while(c = getchar()) putchar(c);

10 CS210 - The University of Auckland

Extra: Compiling & Running in UNIX y Using Unix System(chaos.cs.auckland.ac.nz) ◦ Your source files names should be of the form “*.c” ◦ The assignment will be run using the C compiler (“cc” or “gcc”) ◦ Note: x Try to ensure that you use only standard ANSI C features x The compiler does not generate either error or warning messages. x Compiling Options (check by “man gcc”) x The flag “-ansi” to restrict the compiler to ANSI features. x The flag “-Wall” causes the compiler to display all warning messages. y Steps: ◦ Start SSH Client and login to chaos server ◦ Initially, your location is at UnixHome folder, to get to your ECHome (H:) type .. then cd echome ◦ Write the program in a text editor ◦ Save the file as “myFile.c” in your UnixHome /ECHome folder ◦ Compile the source code by entering cc myFile.c or gcc myFile.c ◦ Run the program by entering ./a.out ◦ Remember to add ./ infront ◦ Rename the computer-executable file cc myFile.c –o myFile ◦ Redirect the output, type ./myFile > myFile.txt

11