+ All Categories
Home > Documents > 1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.

1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.

Date post: 03-Jan-2016
Category:
Upload: camilla-leslie-gallagher
View: 217 times
Download: 1 times
Share this document with a friend

of 36

Click here to load reader

Transcript

Slide 1

Introduction to C Language1COMP 2130 Introduction to Computer Systems

Computing ScienceThompson Rivers University1. Introduction2The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970sInfluenced 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, 2nd Edition, Prentice Hall Referred to as K&R Standard CStandardized in 1989 by ANSI (American National Standards Institute) known as ANSI CInternational standard (ISO) in 1990 which was adopted by ANSI and is known as C89As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99)C++ and CC++ extends C to include support for Object Oriented Programming and other features that facilitate large software development projectsC is not strictly a subset of C++, but it is possible to write Clean C that conforms to both the C++ and C standards.

Elements of a C Program4A 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 filesCompiler: converts source to object code for a specific platformLinker: resolves external references and produces the executable moduleUser program structurethere must be one main function where execution begins when the program is run. This function is called mainint main (void) { ... },int main (int argc, char *argv[]) { ... }UNIX Systems have a 3rd way to define main(), though it is not POSIX.1 compliantint main (int argc, char *argv[], char *envp[])additional local and external functions and variables

A Simple C Program5Create example file: try.cCompile using gcc:gcc o try try.cThe standard C library libc is included automaticallyExecute program./tryNote, I always specify an absolute pathNormal termination:void exit(int status);calls functions registered with at exit()flush output streamsclose all open streamsreturn status value and control to host environment

/* you generally want to * include stdio.h and * stdlib.h * */#include #include

int main (void){ printf(Hello World\n); exit(0);}ex01.cGetting Started6C program files should end with .c.hello.c#include // similar to import statements in Java// stdio.h includes the information about the standard libraryint main()// similar to main method in Java{ printf (hello, world\n); // printf() defined in stdio.hreturn 0;}

How to compile?$ gcc hello.cor$ gcc hello.c -o helloIf you do not have anything wrong, you will see a.out in the same working directory.How to run?$ ./a.outSource and Header files7Just as in Java, place related code within the same module (i.e. file). Header files (*.h) export interface definitionsfunction prototypes, data types, macros, inline functions and other common declarationsDo not place source code (i.e. definitions) in the header file with a few exceptions.inlined codeclass definitionsconst definitionsC preprocessor (cpp) is used to insert common definitions into source filesThere are other cool things you can do with the preprocessor

Another Example C Program8example.c/* this is a C-style comment * You generally want to palce * all file includes at start of file * */#include #include

int main (int argc, char **argv){ // this is a C++-style comment // printf prototype in stdio.hprintf(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 preprocessorto include the contents of the fileat this point in the source file.#define directs preprocessor to define macros.

ex02.cC Standard Header Files9Standard 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, etcstring.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 errorsmath.h math functions: ceil, exp, floor, sqrt, etc.signal.h signal handling facility: raise, signal, etcstdint.h standard integer: intN_t, uintN_t, etctime.h time related facility: asctime, clock, time_t, etc.

C Library Functions: Examples10

The Preprocessor11The 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 alternativedefined() : preprocessor function: 1 if name defined, else 0#if defined(__NetBSD__)

Common features12For 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 typeschar, int, (short & long), float, double

Format specifiers13Summary 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%%% itselfExample14The 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); }ex03.c14Operators15MathematicalSubtraction, also unary minus+Addition*Multiplication/Division%Modulus--Decrement++Increment

Relational >Greater than >=Greater than or equal C

Precedence and Associativity19

20Examplesx =10;y = ++x; y 11x =10;y = x++; y 10

int i = 3, j = 2, k;i++;ij = ++i;ji k = i++;k i k = (--j+3)kj4555647ex04.c21l = 4;n = 3;m = 2;x = l * n + m++; After the assignment to x. m143ex05.c22 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);ex06.cPrecedence and Associativity 23

24Both are lower in precedence than the arithmetic operators.

10 > 1 + 12 10 > (1 + 12) FALSE 0 Associativity: left to right.

intx;x=100;printf(''%d",(x>10)); __?ex07.cLogical Operators in C: Example25#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" ); }}ex08.cExample26See

Answer 27

Comma operator28Lowest precedence of all the operators.Causes a sequence of operations, do this and this and this.Is a binary operator.expression_1, expression_2Associates left to right.

expression_1 is evaluated firstexpression_2 is evaluated second

ex09.cComma operator Ex. 29 The Comma Expression as a whole has the value and type of expression_2.

Conditional Operator (Ternary)30A powerful and convenient operator that replaces certain statements of the if-then-else form.Exp1?Exp2:Exp3

Example31It is also possible to nest ternary

ex10.c31Expressions Vs Statements32An 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.

Symbolic ConstantsTRU-COMP2130C Programming33#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 =a && c < = z) ? c - (z - Z):c;


Recommended