COMP 2130 Intro Computer Systems Thompson Rivers University

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Introduction to C Systems Programming Concepts. Introduction to C A simple C Program A simple C Program –Variable Declarations –printf ( ) Compiling and.
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
Lectures 10 & 11.
Chapter 16 Java Virtual Machine. To compile a java program in Simple.java, enter javac Simple.java javac outputs Simple.class, a file that contains bytecode.
Programming Languages and Paradigms The C Programming Language.
1 pritisajja.info Unlocking the World of Java Programming….. Priti Srinivas Sajja February, 2014 Visit pritisajja.info for detail Future Technology for.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
1 Today’s lecture  Last lecture we started talking about control flow in MIPS (branches)  Finish up control-flow (branches) in MIPS —if/then —loops —case/switch.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
0 Chap. 4 Functions and Program Structure 4.1 Basics of Functions 4.2 Functions Returning Non-integers 4.3 External Variables 4.4 Scope Rules 4.5 Header.
Imperative Programming Prof. Béat Hirsbrunner Amine Tafat, PhD Student Matthias Buchs and Raphaël Lesceux, Graduate Students Department of Informatics.
0 Arrays (1/2) #include /* count digits, white space, others */ main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; for (i = 0; i
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
C Programming. Chapter – 1 Introduction Study Book for one month – 25% Learning rate Use Compiler for one month – 60%
Introduction to C Language
Computer Science 210 Computer Organization Introduction to C.
C Programming A Modern Approach
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Programming Language  C Tutorial Introduction 主講人:虞台文.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Engineering Computing I Chapter 4 Functions and Program Structure.
Introduction to Java Java Translation Program Structure
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Prof. Béat Hirsbrunner Ammar Halabi, PhD student (exercises) Dani Rotzetter, Master student (exercises) Bachelor students : Major in computer science (3rd.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
C is a high level language (HLL)
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 2 : August 28 webpage:
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Lecture 3 Translation.
C++ Lesson 1.
Information and Computer Sciences University of Hawaii, Manoa
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
The Machine Model Memory
Computer Science 210 Computer Organization
C Short Overview Lembit Jürimägi.
User-Defined Functions
11/10/2018.
Computer Science 210 Computer Organization
Scope, Parameter Passing, Storage Specifiers
Your questions from last session
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Getting started Variables Basic C operators Conditionals
Module 2 Variables, Data Types and Arithmetic
Programming Languages and Paradigms
Variables in C Topics Naming Variables Declaring Variables
INTRODUCTION TO C.
Presentation transcript:

COMP 2130 Intro Computer Systems Thompson Rivers University Intro to C Programming Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University

Reliable and efficient programming for power programmers Course Objectives The better knowledge of computer systems, the better programing. Computer System C Programming Language Computer architecture CPU (Central Processing Unit) IA32 assembly language Introduction to C language Compiling, linking, loading, executing Physical main memory MMU (Memory Management Unit) Virtual memory space Memory hierarchy Cache Dynamic memory management Better coding – locality Reliable and efficient programming for power programmers (to avoid strange errors, to optimize codes, to avoid security holes, …) Not the replacement of IPv6; Inter-transition mechanism; But if IPv6 would fail TRU-COMP2130 C Programming

Course Contents Introduction to computer systems: B&O 1 Introduction to C programming: K&R 1 – 4 Data representations: B&O 2.1 – 2.4 C: advanced topics: K&R 5.1 – 5.9, 5.11, 6 – 8 Introduction to IA32 (Intel Architecture 32): B&O 3.1 – 3.8, 3.13 Compiling, linking, loading, and executing: B&O 7 (except 7.12) Dynamic memory management – Heap: B&O 9.9.1 – 9.9.2, 9.9.4 – 9.9.5, 9.11 Code optimization: B&O 5.1 – 5.6, 5.13 Memory hierarchy, locality, caching: B&O 5.12, 6.1 – 6.3, 6.4.1 – 6.4.2, 6.5, 6.6.2 – 6.6.3, 6.7 Virtual memory (if time permits): B&O 9.4 – 9.5 Not the replacement of IPv6; Inter-transition mechanism; But if IPv6 would fail TRU-COMP2130 C Programming

Unit Learning Objectives Use cc (or gcc) to compile C programs. Write a C program with the common (very similar) syntaxes with Java. Use printf() library function to print messages. Use define statements for constants. Use getchar() and putchar() for I/O. Use of integer values as Boolean values. Use a char array as a string. Use bit operators to manipulate bits in a given integer. Understand the scope of external identifiers. Distinguish signed integer types and unsigned integer types. Use register variables for indexing arrays. Use conditional inclusion statements with #if, #elif, … . … TRU-COMP2130 C Programming

Unit Contents Introduction Types, Operators, and Expressions Control Flow Functions and Program Structure TRU-COMP2130 C Programming

1. Introduction Only the topics that are different from Java will be discussed. TRU-COMP2130 C Programming

Getting Started C program files should end with “.c”. How to compile? hello.c #include <stdio.h> // similar to import statements in Java // stdio.h includes the information about the standard library main() // similar to main method in Java { printf (“hello, world\n”); // printf() defined in stdio.h } How to compile? $ gcc hello.c or $ 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 TRU-COMP2130 C Programming

Very similar primitive data types Same control structures 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. Very similar primitive data types char, short, int, long, float, double, … Same control structures if, if-else, for, while, do-while, switch Same operators (we will discuss some new ones later.) +, -, *, /, %, =, ==, !=, &&, ||, … Can you write a program to convert Fahrenheit temperature to Celsius temperature? The conversion formula: C = 5 / 9 × (F – 32) TRU-COMP2130 C Programming

#include ... /* print Fahrenheit-Celsius table for fahr = 0, 20, 40, ..., 300, using a loop */ main() { int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature scale */ upper = 300; // upper limit step = 20; // step size fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; // integer value? printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } TRU-COMP2130 C Programming

printf("%d\t%d\n", fahr, celsius); %d specifies an integer argument (d: decimal). Output 1 -17 20 -6 40 4 ... Can we print better? Like 1 -17 20 -6 40 4 printf("%3d\t%6d\n", fahr, celsius); TRU-COMP2130 C Programming

Is there any problem in the above output? 1 -17 20 -6 40 4 ... Is there any problem in the above output? The Celsius temperatures in the previous out are not accurate. For example 0o F is -17.8o C. Then? We can use float data type for fahr and celsius instead of int. float fahr, celsius; Then how to print real numbers using printf()? celsius = 5 * (fahr-32) / 9; // okay? printf("%3.0f\t%6.1f\n", fahr, celsius); %f specifies a floating point argument (f: floating point). 6.1 means 1 decimal out of 6 digits. TRU-COMP2130 C Programming

Some easy errors: printf("%d\t%6.1f\n", fahr, celsius); ??? printf("%3.0f\t%6.1f\n", fahr); ??? printf("%6.1f\n", fahr, celsius); ??? TRU-COMP2130 C Programming

Summary of printf() format specifiers %d print as decimal integer %6d print as decimal integer, at least 6 characters wide %f print as floating point %6f print as floating point, at least 6 characters wide %.2f print as floating point, 2 characters after decimal point %6.2f print as floating point, at least 6 characters wide and 2 after decimal point Other format specifiers %o for octal %x for hexadecimal %c for character %s for character string %% % itself TRU-COMP2130 C Programming

Symbolic Constants #define name replacement_list main() { TRU-COMP2130 #include <...> #define LOWER 0 // similar to final variable in Java #define UPPER 300 #define STEP 20 main() { float fahr, celsius; for (fahr = ... ; fahr <= ... ; fahr = fahr + ...) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); } TRU-COMP2130 C Programming

Symbolic Constants #define name replacement_list main() { TRU-COMP2130 #include <stdio.h> #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); } TRU-COMP2130 C Programming

Character Input and Output #include <stdio.h> /* 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(); } Where did getchar(), EOF, and putchar() come from? Let’s run this program to understand I/O better. TRU-COMP2130 C Programming

What if we use the follow code instead? #include <stdio.h> /* 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 =. TRU-COMP2130 C Programming

Operator precedence rules () [] -> . ! ~ - (unary) + (unary) * & sizeof ++ -- * / % + - << >> < <= > >= == != & ^ | && || = += -= *= /= %= &= |= ^= <<= >>= TRU-COMP2130 C Programming

Boolean values? Syntax error? while (c = getchar() != EOF) Let’s assume getchar() returns ‘A’. Then getchar() != EOF becomes TRUE. The data type of c is int. Is there a boolean data type in C? No. 0 is FALSE and non-zero value is considered as TRUE in C. Hence getchar() != EOF becomes 1, and c has 1. while(c) -> while(1). The loop repeats. TRU-COMP2130 C Programming

Arrays TRU-COMP2130 #include <stdio.h> /* count digits, white space, others */ main() { int c, i, nwhite, nother, ndigit[10]; // very similar to Java nwhite = nother = 0; // really necessary? for (i = 0; i < 10; ++i) ndigit[i] = 0; while ((c = getchar()) != EOF) if (c >= '0' && c <= '9') ndigit[c-'0']++; else if (c == ' ' || c == '\n' || c == '\t') ++nwhite; else nother++; printf("digits ="); for (i = 0; i < 10; i++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); } TRU-COMP2130 C Programming

A character, e.g., ‘3’, is an integer value. int c = ‘3’; is valid. ASCII table TRU-COMP2130 C Programming

Functions TRU-COMP2130 #include <stdio.h> int power(int m, int n); // function declaration // What if it is not declared before // main()? main() { int i; for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2, i), power(-3, i), i); return 0; } /* power: raise base to n-th power; n >= 0 */ int power(int base, int n) int i, p; ... // How to implement? TRU-COMP2130 C Programming

TRU-COMP2130 ... for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2,i), power(-3,i), i); return 0; } /* power: raise base to n-th power; n >= 0 */ int power(int base, int n) { int i, p; p = 1; for (i = 1; i <= n; i++) p = p * base; return p; TRU-COMP2130 C Programming

Arguments /* power: raise base to n-th power; n >= 0; version 2 */ int power(int base, int n) { int p; for (p = 1; n > 0; n--) p = p * base; return p; } base, n and p are local variables that are used only in power(). When the function is called (or also called invoked), the values will be copied (oac passed) into base and n. Even if those variables are updated with other values, the new values will not be passed back to the caller function. How is this implemented in main memory? This type of function calling is called call by value. TRU-COMP2130 C Programming

Character Arrays In the same file int getline(char s[], int lim) #include <stdio.h> #define MAXLINE 1000 int getline(char line[], int maxline); void copy(char to[], char from[]); main() { int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; // longest line saved max = 0; while ((len = getline(line, MAXLINE)) > 0) if (len > max) { max = len; copy(longest, line); } if (max > 0) printf("%s", longest); return 0; ... int getline(char s[], int lim) { int c, i; for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { ++i; } s[i] = '\0'; // “...’\0’” return i; void copy(char to[], char from[]) int i; i = 0; while ((to[i] = from[i]) != '\0')

In main(), while ((len = getline(line, MAXLINE)) > 0) The data type of line[] is an array. getline() can change the contents in line[], and the change in line[] can be used in main(). Very similar to Java. This type of function calling is called call by reference. How is this implemented in main memory? line represents MAXLINE variables - line[0], line[1], ..., line[MAXLINE-1]. How? Address should be passed. line contains the address of the first byte of line[0]. line[i] is the memory area pointed by the address line + sizeof(char) * i. Main memory addr value var … def abc line ‘C’ line[0] abc+1 ‘O’ line[1] TRU-COMP2130 C Programming

In getline(), int getline(char s[], int lim) The data type of the first parameter is an array. The address stored in line in main() is passed into s. Therefore s[i] will become equal to line[i]. Any change in this variable will be preserved so that the caller can use the change. This type of function calling is called call by reference. s[i] = '\0'; After all the characters are stored in s[] till EOF or ‘\n’, ‘\0’ is stored to mark the end of the character string. That is, a string is a list of characters with the end of ‘\0’, and a char array is usually used to keep a string. This is very important. TRU-COMP2130 C Programming

In main(), if (max > 0) printf("%s", longest); %s is used to print a character string. The argument is a char array, not longest[], nor longest[0], and … What is the data type of longest? char longest[MAXLINE]; What value is stored in longest? The address of the first byte of longest[0] to represent all longest[0], longest[1], …. Can a char array be a character string? Yes. printf() with %s will try to print characters pointed by longest(, i.e., longest[0], longest[1], …,) until the character becomes ‘\0’. TRU-COMP2130 C Programming

What is the output? TRU-COMP2130 char name[256], tmp[256]; name[0] = ‘C’; name[1] = ‘O’; name[2] = ‘M’; name[3] = ‘P’; name[4] = ‘\0’; // it is very important. printf(“course number = %s\n”, name); name[5] = ‘ ’; name[6] = ‘2’; name[7] = ‘1’; name[8] = ‘3’; name[9] = ‘0’; name[10] = ‘\0’; // it is very important. What is the output? TRU-COMP2130 C Programming

External Variables and Scope In the same file #include <stdio.h> #define MAXLINE 1000 int max; // similar to instance in Java char line[MAXLINE]; char longest[MAXLINE]; int getline(void); void copy(void); main() { int len; extern int max, extern char longest[]; max = 0; while ((len = getline()) > 0) if (len > max) { max = len; copy(); } if (max > 0) /* there was a line */ printf("%s", longest); return 0; int getline(void) { int c, i; // extern char line[]; // no need to declare for (i = 0; i < MAXLINE – 1 && (c=getchar)) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { ++i; } line[i] = '\0'; return i; void copy(void) int i; // extern char line[], longest[]; i = 0; while ((longest[i] = line[i]) != '\0')

Visible to every function in the file #include … … #define … // declaration of global variables // declaration (i.e., definitions) of functions // implementation of functions { } Any identifier declared early is visible in the same block or sub-blocks. Visible to every function in the file TRU-COMP2130 C Programming

2. Types, Operators, Expressions TRU-COMP2130 C Programming

Data Types and Sizes Primitive data types C Java Size char, unsigned char byte 1B char in Java uses 2Bs. short, unsigned short short 2Bs int, unsigned int int 4Bs long, unsigned long long 8Bs // there is no unsigned in Java float float 4Bs double double 8Bs // boolean? TRUE: any non-zero value, boolean in Java FALSE: zero // string? “...”: with ‘\0’ at the end String in Java sizeof(data_type) or sizeof(variable) gives the number of bytes used. TRU-COMP2130 C Programming

Constants int 1234, long 12345678L double 123.4, 1e-3 float 123.4F printf() format specifiers %u unsigned integers %l long integers %lu unsigned long integers %e float, double TRU-COMP2130 C Programming

Operators Arithmetic operators Relational operators = assignment + addition ++ increment by one; sometimes confusing - subtraction -- decrement by one; sometimes confusing * multiplication / division; integer division % modulo Relational operators > >= < <= TRU-COMP2130 C Programming

Reference operators– will be discussed later. Boolean operators == != && AND not bitwise AND || OR not bitwise OR Reference operators– will be discussed later. TRU-COMP2130 C Programming

Bitwise Operators Examples | bitwise OR & bitwise AND ^ XOR ~ 1’s complement << shift left >> arithmetic shift right (the left most bit will be copied.) Examples Exercise 2-6 setbits(x, p, n, y) Exercise 2-7 invert(x, p, n) Exercise 2-8 rightrot(x, n) IPv4 address conversion Check if a target bit in an integer is 1. Get the first three bytes in an integer. … TRU-COMP2130 C Programming

3. Control Flow Statement Block, or compound statement …; Block, or compound statement { … } The same control structures as Java if, … for, while, do-while switch break, continue You must know them all already. TRU-COMP2130 C Programming

Goto and Labels Better not use goto statements for (i = 0; i < n; i++) for (j = 0; j < m; j++) if (a[i] == b[j]) goto found; /* didn't find any common element */ ... found: /* got one: a[i] == b[j] */ Better not use goto statements Can you convert the above code so that you would not use goto? TRU-COMP2130 C Programming

4. Functions and Program Structure Function in C is the same as method in Java. return-type function-name(argument declarations) Various parts may be absent. TRU-COMP2130 C Programming

External Variables If a large number of variables must be shared among functions, external variables (or also called global variables) are more convenient and efficient than long argument lists. External variables are declared outside of any function, usually with initial values. Automatic variables (local variables and parameters) are internal to a function; they come into existence when the function is entered, and disappear when it is left. External variables, on the other hand, are permanent, so they can retain values from one function invocation to the next. Thus if two functions must share some data, yet neither calls the other, it is often most convenient if the shared data is kept in external variables rather than being passed in and out via arguments. TRU-COMP2130 C Programming

Scope Rules The scope of a name is the part of the program within which the name can be used. The scope of an external variable or a function lasts from the point at which it is declared to the end of the file being compiled. main() { ... } int sp = 0; double val[MAXVAL]; void push(double f) { ... } double pop(void) { ... } Is sp visible in push()? Can sp and pop() be used in main()? TRU-COMP2130 C Programming

Can we make external variables declared in file1 be used in file2? extern int sp; extern double val[]; void push(double f) { ... } double pop(void) { ... } in file2: int sp = 0; double val[MAXVAL]; TRU-COMP2130 C Programming

Static Variables The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file being compiled. External static thus provides a way to hide names from other files. static char buf[BUFSIZE]; // only in this file static int bufp = 0; // only in this file int getch(void) { ... } void ungetch(int c) { ... } Static in Java has a bit different meaning. TRU-COMP2130 C Programming

Register Variables A register declaration advises the compiler that the variable in question will be heavily used. The idea is that register variables are to be placed in machine registers, which may result in smaller and faster programs. But compilers are free to ignore the advice. register int x; register char c; f(register unsigned m, register long n) { register int i; ... } Usually for index variables used in loop structures TRU-COMP2130 C Programming

Initialization Very similar to Java In the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero; but automatic and register variables have undefined (i.e., garbage) initial values. TRU-COMP2130 C Programming

The C Preprocessor File inclusion Macro substitution #include “filename” // from the working dir or #include <filename> // from the standard dir Macro substitution #define name replacement_text #define max(A, B) ((A) > (B) ? (A) : (B)) Conditional inclusion #if !defined(HDR) // or #ifndef HDR #define HDR /* contents of hdr.h go here */ #endif TRU-COMP2130 C Programming

#if SYSTEM == SYSV #define HDR "sysv.h" #elif SYSTEM == BSD #define HDR "bsd.h" #elif SYSTEM == MSDOS #define HDR "msdos.h" #else #define HDR "default.h" #endif #include HDR TRU-COMP2130 C Programming