320 likes | 438 Views
Introduction to C Programming. Overview of C Hello World program Unix environment C programming basics. Overview of C. Preceded by BCPL and B Developed by Dennis Ritchie Bell Labs in 1972 Portable (machine-independent) Used in UNIX, networks. Hello World Program.
E N D
Introduction to C Programming • Overview of C • Hello World program • Unix environment • C programming basics
Overview of C • Preceded by BCPL and B • Developed by Dennis Ritchie • Bell Labs in 1972 • Portable (machine-independent) • Used in UNIX, networks
Hello World Program /*Will ouput "Aloha!"*/ #include <stdio.h> int main(void) { printf("Aloha!\n"); return 0; }
Hello World Program /*comments*/ /*Two lines of comments*/ • Ignored by the C compiler
Hello World Program #include <stdio.h> • Directive to C preprocessor • # (pound sign) – line processed by preprocessor before the program is compiled • Tells preprocessor to include contents of stdio.h file in the program • stdio.h - standard input/output header file • Contains information & declarations about functions • In this case, the printf library function
Hello World Program int main(void){return 0;} • int – return type of function • return 0; • Returns 0 to operating system • Indicates that program executed successfully • main • Every program consists of 1 or more functions • Must have a main function • (void) – function arguments • {} – body of function = left & right brackets (block)
6 Phases to Execute C Program • Edit – write program & store on disk • Creates file: program.c • Preprocess – add other files & text replacement • Compile – creates object (machine) code • Creates file: program.o • Link – links code & libraries to make executable • Creates file: a.out • Load – takes from disk & put in memory • Execute – CPU executes each instruction
UNIX Environment • Edit program with Emacs (Vi or Pico) • emacsprogram.c • Preprocess, Compile & Link (using the GNU C compiler) • gccprogram.c (will make “a.out”) • gccprogram.c -o program (“program” will be the executable) • Load & Execute • ./a.out(./program), or just “a.out”
Makefile • You can compile & link separately • gcc –c program.c (creates “program.o”) • gcc program.o (creates “a.out”) • Or gcc program.o –o program (creates “program”) • Easier to do with makefile • A file that tells how to build executables from multiple files • Name of the file is “makefile” • To run this file, type “make” • The command “make” finds the “makefile” and executes the commands listed in it
Creating a Makefile • Makefiles consist of sets of three lines • Target: list of dependencies • <tab>Commands needed to build target • Blank line (newline character) • Example makefile: • program: program.o • gcc program.o -o program • program.o: program.c • gcc -c program.c • Note: the last line in this file is a newline!
Running a Makefile • Type “make” • Should get the following output • gcc -c program.c • gcc program.o -o program • Type “./program” to run executable • "." is the current directory • ./program is the complete path to program
Example Program • In the UHUNIX environment, run the following commands on the commandline • cpaloha.cprogram.c • make • ./program (or just “program”)
Problems with Makefile • UNIX make program is unreasonably picky about the format of the make file • Must use a tab at the beginning of each command line • Must put a blank line (newline character - \n) after each group of statements, including at the end of the file • If you create it on your PC & ftp (file transfer protocol) it to UNIX, the newline characters will cause problems in UNIX, so need to create with a UNIX editor
File Transfer • If you are creating files on your PC & ftp (file transfer protocol) to UNIX, then might get error message • warning: invalid white space character in directive • Why? • UNIX newline is one character (0x0A) • PC newline is two characters • 0x0Dh = carriage return • 0x0Ah = line feed • Solution: make sure you ftp in ASCII mode, not in binary mode • In SSH click: Operation <File Transfer Mode <ASCII, binary,for auto select
Variables int x=1, y=2, z=3; • Variables declared at beginning of a function • Before any executable statements • Should initialize variables when declare them • Uninitialized variables have unpredictable values • Number of bytes (= 8 bits) for each data type (Unix) • char = 1 byte (-128 to 127) • short = 2 bytes (-32768 to 32767) • int & long = 4 bytes (-2,147,483,648 to +2,147,483,647) • float = 4 bytes (± ~10-44 to ~1038 ) • double = 8 bytes (± ~10-323 to ~10308 )
Data Types • Unsigned integers • Represents positive integers only • Example: ASCII character codes • Not necessary to indicate a sign, so all 8 or 16 bits can be used for the magnitude: • unsigned char = 1 byte = 8 bits = 28 = 256 (0 to 255) • unsigned short = 2 bytes = 16 bits = 216 = 65,536 (0 to 65,535) • unsigned int & unsigned long = 4 bytes = 32 bits = 232 = 4,294,967,296 (0 to 4,294,967,295)
Data Types • Signed integers • Default is signed (int = signed int) • Represents positive and negative integers • MSB (Most Significant Bit – leftmost bit) used to indicate sign • 0 = positive, 1 = negative • (LSB = Least Significant Bit – rightmost bit)
Variable Names • Restrictions • Made up of letters & digits • 1st character must be a letter • Underscore (“_”) counts as a letter • Often used in library routines • Case sensitive • APPLE & apple are different variables • Less than 31 characters • Cannot use reserved keywords • auto, break, case, …, void, volatile, while
Formatted Output - Printf • int printf(char *format, arg1, arg2, …) • Translates internal values to character output • Returns the number of characters printed
Conversion Specifiers • u • Unsigned decimal • X • Unsigned hexadecimal • UPPERCASE output for hex letters • % • Print a “%” • d • Signed decimal integer • x • Unsigned hexadecimal • lowercase output for hex letters • c • Single character • f • Floating points • m.dddddd
Variable Output • See output.c as an example • The output for the same variable will differ based on what kind of format is specified
Arithmetic Operators • ( ) • Parenthesis (highest precedence) • *, /, % • Multiplication, division, modulus • Evaluated left to right • +, - • Addition and subtraction • Evaluated left to right
Arithmetic Operators • Integer division produces an integer result • 1 / 2 evaluates to 0 (0.5, but no rounding up!) • 19 / 5 evaluates to 3 (3.8, but no rounding up!) • Modulus (%) = remainder after division • 1 % 2 evaluates to 1 (0 remainder 1) • 17 % 5 evaluates to 2 (3 remainder 2) • Implicit conversion – if an operation has operands of different types, the “narrower” one will be converted to the “wider” one • 2.0 / 5 evaluates to 0.4 (a float)
Equality, Relational Operators • Equality operators • == (equal) – common error: = instead of == • != (not equal) • Relational operators • > (greater than) • < (less than) • >= (greater than or equal) • <= (less than or equal) • Will return a 0 (false) or 1(true)
if Control Structure • A program can make a decision using the if control structure and the equality or relational operators /*See if.c*/ #include <stdio.h> int main(void) { if(1 > 2) {printf("%d > %d\n",1,2);} if(1 <= 2) { printf("%d <= %d\n",1,2);} return 0; }
Class Exercise 1 • Trace the following code, then run it to see if you get your expected output • exercise1.c
Input in C /*See input.c*/ #include <stdio.h> int main(void){ int x = 0; printf("Enter an integer: "); scanf("%d", &x); printf("The integer is %d\n", x); return 0; }
scanf Function • scanf("%d", &x); • First argument: format control string • Indicates type of data to be entered • Second argument: location in memory • Use an ampersand (&) to give the address where the variable is stored • The computer will wait for the user to enter a value and press the “Enter” key
Class Exercise 2 • Write a program that does the following: • inputs two integers • adds them together • outputs the sum • determines if the sum is a multiple of 3 (evenly divisible by 3)