Download presentation
Presentation is loading. Please wait.
Published byCamilla Leslie Gallagher Modified over 9 years ago
1
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University
2
1. Introduction 2 The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970s Influenced by ALGOL 60 (1960), CPL (Cambridge, 1963), BCPL (Martin Richard, 1967), B (Ken Thompson, 1970) Traditionally used for systems programming, though this may be changing in favor of C++ Traditional C: The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2 nd Edition, Prentice Hall Referred to as K&R
3
Standard C Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C International standard (ISO) in 1990 which was adopted by ANSI and is known as C89 As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99) C++ and C ◦ C++ extends C to include support for Object Oriented Programming and other features that facilitate large software development projects ◦ C is not strictly a subset of C++, but it is possible to write “Clean C” that conforms to both the C++ and C standards.
4
Elements of a C Program 4 A C development environment includes ◦ System libraries and headers: a set of standard libraries and their header files. For example see /usr/include and glibc. ◦ Application Source: application source and header files ◦ Compiler: converts source to object code for a specific platform ◦ Linker: resolves external references and produces the executable module User program structure ◦ there must be one main function where execution begins when the program is run. This function is called main int main (void) {... }, int main (int argc, char *argv[]) {... } UNIX Systems have a 3 rd way to define main(), though it is not POSIX.1 compliant int main (int argc, char *argv[], char *envp[]) ◦ additional local and external functions and variables
5
A Simple C Program 5 Create example file: try.c Compile using gcc: gcc –o try try.c The standard C library libc is included automatically Execute program./try Note, I always specify an absolute path Normal termination: void exit(int status); ◦ calls functions registered with at exit() ◦ flush output streams ◦ close all open streams ◦ return status value and control to host environment /* you generally want to * include stdio.h and * stdlib.h * */ #include int main (void) { printf(“Hello World\n”); exit(0); }
6
Getting Started 6 C program files should end with “.c”. ◦ hello.c #include // similar to import statements in Java // stdio.h includes the information about the standard library int main()// similar to main method in Java { printf (“hello, world\n”); // printf() defined in stdio.h return 0; } How to compile? ◦ $ gcc hello.cor ◦ $ gcc hello.c -o hello ◦ If you do not have anything wrong, you will see a.out in the same working directory. How to run? ◦ $./a.out
7
Source and Header files 7 Just as in Java, place related code within the same module (i.e. file). Header files (*.h) export interface definitions ◦ function prototypes, data types, macros, inline functions and other common declarations Do not place source code (i.e. definitions) in the header file with a few exceptions. ◦ inline’d code ◦ class definitions ◦ const definitions C preprocessor (cpp) is used to insert common definitions into source files There are other cool things you can do with the preprocessor
8
Another Example C Program 8 example.c /* this is a C-style comment * You generally want to palce * all file includes at start of file * */ #include int main (int argc, char **argv) { // this is a C++-style comment // printf prototype in stdio.h printf(“Hello, Prog name = %s\n”, argv[0]); exit(0); } /* comments */ #ifndef _STDIO_H #define _STDIO_H... definitions and protoypes #endif /usr/include/stdio.h /* prevents including file * contents multiple * times */ #ifndef _STDLIB_H #define _STDLIB_H... definitions and protoypes #endif /usr/include/stdlib.h #include directs the preprocessor to “include” the contents of the file at this point in the source file. #define directs preprocessor to define macros.
9
C Standard Header Files 9 Standard Headers you should know about: ◦ stdio.h – file and console (also a file) IO: perror, printf, open, close, read, write, scanf, etc. ◦ stdlib.h - common utility functions: malloc, calloc, strtol, atoi, etc ◦ string.h - string and byte manipulation: strlen, strcpy, strcat, memcpy, memset, etc. ◦ ctype.h – character types: isalnum, isprint, isupper, tolower, etc. ◦ errno.h – defines errno used for reporting system errors ◦ math.h – math functions: ceil, exp, floor, sqrt, etc. ◦ signal.h – signal handling facility: raise, signal, etc ◦ stdint.h – standard integer: intN_t, uintN_t, etc ◦ time.h – time related facility: asctime, clock, time_t, etc.
10
C Library Functions: Examples 10
11
The Preprocessor 11 The C preprocessor permits you to define simple macros that are evaluated and expanded prior to compilation. Commands begin with a ‘#’. Abbreviated list: ◦ #define : defines a macro ◦ #undef : removes a macro definition ◦ #include : insert text from file ◦ #if : conditional based on value of expression ◦ #ifdef : conditional based on whether macro defined ◦ #ifndef : conditional based on whether macro is not defined ◦ #else : alternative ◦ #elif : conditional alternative ◦ defined() : preprocessor function: 1 if name defined, else 0 #if defined(__NetBSD__)
12
Common features 12 ◦ For the statement printf (“hello, world\n”); ◦ “…” is a character string. This is also called a string constant. printf() is a library function to print a string to the terminal. The C library function int scanf(const char *format,...) reads formatted input from stdin. Data types - primitive data types char, int, (short & long), float, double
13
Format specifiers 13 Summary of printf() format specifiers %dprint as decimal integer %6dprint as decimal integer, at least 6 characters wide %fprint as floating point %6fprint as floating point, at least 6 characters wide %.2fprint as floating point, 2 characters after decimal point %6.2fprint as floating point, at least 6 characters wide and 2 after decimal point Other format specifiers %ofor octal %xfor hexadecimal %cfor character %sfor character string %% itself
14
Example 14 ◦ The following example shows the usage of scanf() function. #include int main() { char str1[20], str2[30]; printf("Enter name: "); scanf("%s", &str1); printf("Enter your website name: "); scanf("%s", &str2); printf("Entered Name: %s\n", str1); printf("Entered Website:%s\n", str2); return(0); }
15
Operators 15 Mathematical –Subtraction, also unary minus +Addition *Multiplication /Division %Modulus --Decrement ++Increment Relational >Greater than >=Greater than or equal <Less than <=Less than or equal = =Equal !=Not equal
16
Operators 16 Logical Operators: &&AND ||OR !NOT
17
Control structures 17 Control structures if, if-else, for, while, do-while, switch
18
Exercise 18 write a program to convert Fahrenheit temperature to Celsius temperature, using the given formula formula: ◦ Ask user for an option for C -> F Or F -> C
19
Precedence and Associativity 19
20
20 Examples x =10;y = ++x; y 11 x =10;y = x++; y 10 int i = 3, j = 2, k; i++;i j = ++i;ji k = i++;k i k = (--j+3)kj 4 5 5 5 6 4 7
21
21 l = 4; n = 3; m = 2; x = l * n + m++; After the assignment to x. m 14 3
22
22 int a,b; a = 1; b = 12; printf (“a+++b = %d\n”, a+++b); a = 1; b = 12; printf (“a++ +b = %d\n”, a++ +b); a = 1; b = 12; printf (“a+ ++b =% d\n”, a+ ++b);
23
Precedence and Associativity 23
24
24 Both are lower in precedence than the arithmetic operators. 10 > 1 + 12 10 > (1 + 12) FALSE 0 Associativity: left to right. int x; x = 100; printf(''%d", (x>10)); __?
25
Logical Operators in C: Example 25 #include main() { int a = 5; int b = 20; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }
26
Example 26 See
27
Answer 27
28
Comma operator 28 Lowest precedence of all the operators. Causes a sequence of operations, “do this and this and this…”. Is a binary operator. expression_1, expression_2 Associates left to right. expression_1 is evaluated first expression_2 is evaluated second
29
Comma operator – Ex. 29 The Comma Expression as a whole has the value and type of expression_2.
30
Conditional Operator (Ternary) 30 A powerful and convenient operator that replaces certain statements of the if-then-else form. Exp1 ? Exp2: Exp3
31
Example 31 It is also possible to nest ternary
32
Expressions Vs Statements 32 An expression in C is any valid combination of operators, constants, functions and variables. A statement is a valid expression followed by a semicolon. Func1(); A function call as a statement. Y = X + Y; An assignment statement.
33
Symbolic Constants TRU-COMP2130 C Programming 33 #define name replacement_list #include #define LOWER 0// similar to final variable in Java #define UPPER 300 #define STEP 20 main() { float fahr, celsius; for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); }
34
Character Input and Output 34 #include /* copy input to output; 1st version */ main() { int c; c = getchar();// in order to read a character while (c != EOF) {// EOF is defined in stdio.h. // EOF means End of File, ^D. putchar(c);// in order to print a character c = getchar(); } }
35
35 #include /* copy input to output; 2nd version */ main() { int c; while ((c = getchar()) != EOF)// okay? putchar(c); } What if we use the follow code instead? while (c = getchar() != EOF) The above code is equivalent to while (c = (getchar() != EOF)) This is because the precedence of != is higher than =
36
Think Idea 36 c = (c > =‘a’ && c < = ‘z’) ? c - (‘z’ - ‘Z’):c;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.