200 likes | 299 Views
Computer Science 210 Computer Organization. Introduction to C. Origins. Developed in the 1970s by Brian Kernighan and Dennis Ritchie at ATT Bell Labs They also developed UNIX Much of UNIX is written in C, and C is the preferred language for developing UNIX system tools. Classification.
E N D
Computer Science 210Computer Organization Introduction to C
Origins • Developed in the 1970s by Brian Kernighan and Dennis Ritchie at ATT Bell Labs • They also developed UNIX • Much of UNIX is written in C, and C is the preferred language for developing UNIX system tools
Classification • C is an imperative language (function definitions, but no classes and objects) • Produces very efficient compiled code • Not very safe (missing some compile-time and run-time error checks)
A Simple C Program • One or more #include directives (like Python imports) • One and only one main function (like Java’s main method) • Can have other function definitions, global variables, type synonyms, etc.
A First Program /* Author: Ken Lambert This program outputs the string "Hello world!" */ #include <stdio.h> int main(){ printf("Hello world!\n"); } • /* */ enclose a program comment • #include is a preprocessor directive • stdio is a library of I/O resources • printf is an output function • main does not return a value for now • All statements must end with a ; • {} enclose blocks or sequences of statements
Compile, Link, and Run • Edit and save the source file with a .c extension • Run gcc –o <filename> <filename>.c • If no errors, run ./<filename>
Program Development Create source code Include code from library header files, expand macros, etc. Editor Preprocessor Compiler Translate to machine code Linker Add library code Loader Place code in appropriate memory locations Runtime System Execute code
Useful Standard Libraries • A header file contains function headers that allow your program to reference the library’s functions • The preprocessor combines these headers with your source program • The linker hooks these references to the compiled object code of the library
Constants, Numbers, and Variables /* This program prints the amount of interest. */ #include <stdio.h> #define INTEREST_RATE .06 int main(){ double principal = 10000.00; printf("Interest is %.2f\n", INTEREST_RATE * principal); } • #define is a preprocessor macro that defines a global constant • Variables must be declared with a data type, using the syntax • <data type> <variable> [ = <expression> ];
More on Variables int anInt = 500; double aDouble = 4.33; char aLetter = 'a'; int garbage; printf("%d %.2f %d %d\n", // Outputs 500 4.33 97 32767 anInt, aDouble, aLetter, garbage); • Basic numeric types are double, float, int, and char • Uninitialized variables contain garbage!
More on printf int anInt = 500; double aDouble = 4.33 double sum = anInt + aDouble; printf("The sum of %d and %.2f is %.2f\n", anInt, aDouble, sum); • printf builds a formatted string, like Python’s % operator • The format flags d, f, and s are used for integers, doubles, and strings, respectively • Field widths can be specified (a signed integer following %) • Precision for doubles can also be specified
Character Output with putchar char aLetter = 'a'; printf("%d\n", aLetter); // Outputs 97 putchar(aLetter); // Outputs a putchar('\n'); A character is automatically treated as an integer (its ASCII value) in many contexts
Weak Data Typing! int anInt = 97; double aDouble = 4.56; char aLetter = 'A'; int four = aDouble; int letterB = aLetter + 1; char lettera = anInt; // Outputs 4 66 97 B a printf("%d %d %d ", four, letterB, lettera); putchar(letterB); putchar(' '); putchar(lettera); putchar('\n'); All numeric types are compatible with each other, no need for explicit type conversions (casts)
Count-Controlled Loops char aLetter; for (aLetter = 'A'; aLetter <= 'Z'; aLetter++) putchar(aLetter); char aLetter = 'A'; while (aLetter <= 'Z'){ putchar(aLetter); aLetter++; // Same as aLetter = aLetter + 1; } Increment operator ++ modifies the variable Boolean values are 0 (meaning false) and any other value (meaning true)
Input with scanf /* This program prints sum of two input integers. */ #include <stdio.h> int main(){ int first, second; printf("Enter a number: "); scanf("%d", &first); printf("Enter a number: "); scanf("%d", &second); printf("The sum is %d\n", first + second); } scanf expects a format string with an input type flag (%f works with float, but not double) The input variable is preceded by the & symbol, which indicates “address of”
Sentinel-Based Loop and Cast Operators int sum = 0; int count = 0; int number; printf("Enter a number or 0 to stop: "); scanf("%d", &number); while (number){ sum += number; count++; printf("Enter a number or 0 to stop: "); scanf("%d", &number); } if (count > 0) printf("The average is %f\n", sum / (double) count); else printf("No numbers entered\n"); The cast operator has the syntax (<type name>) <expression> Note the Boolean expression (number)
Defining a Function /* This program prints the factorial of 6. */ #include <stdio.h> int factorial(int n){ if (n == 1) return 1; else return n * factorial(n – 1); } int main(){ printf("The factorial of 6 is %d\n", factorial(6)); } A function has a return type, which should be void if no value is returned
Top-Down Implementation /* This program prints the factorial of 6. */ #include <stdio.h> int main(){ printf("The factorial of 6 is %d\n", factorial(6)); } intfactorial(intn){ if (n == 1) return 1; else return n * factorial(n - 1); } Functions can be defined in any order (this one goes top-down)
Using Function Prototypes /* This program prints the factorial of 6. */ #include <stdio.h> int factorial(int n); // Prototype of factorial int main(){ printf("The factorial of 6 is %d\n", factorial(6)); } int factorial(int n){ // Implementation of factorial if (n == 1) return 1; else return n * factorial(n - 1); } A function prototype is the function’s header The function implementation comes later
Scope Rules /* This program prints the area of a circle, given its input radius. */ #include <stdio.h> #define PI 3.1416 double area(doubler); intmain(){ float radius; printf("Enter the radius: "); scanf("%f", &radius); printf("The area is %f\n", area(radius)); } double area(doubler){ return PI * r* r; } Global: PI, main, areaLocal: radius, r