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

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

C Programming Day 1 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
Lecture 2 Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Prof. Béat Hirsbrunner Fulvio Frapolli, PhD Student (exercises) Bachelor students : - Major in computer science (first year, 2nd term) - Major in information.
Guide To UNIX Using Linux Third Edition
Basic Input/Output and Variables Ethan Cerami New York
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C Programming. Chapter – 1 Introduction Study Book for one month – 25% Learning rate Use Compiler for one month – 60%
An Introduction to C Programming Geb Thomas. Learning Objectives Learn how to write and compile a C program Learn what C libraries are Understand the.
Introduction to C Language
C Programming Lecture 5. Precedence and Associativity of Operators b Rules of associativity and precedence of operators determine precisely how expressions.
Computer Science 210 Computer Organization Introduction to C.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Introduction to C Programming Summer 2014 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Programming I Introduction Introduction The only way to learn a new programming language is by writing programs in it. The first program to.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
Lecture 1 cis208 January 14 rd, Compiling %> gcc helloworld.c returns a.out %> gcc –o helloworld helloworld.c returns helloworld.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Lexical Elements, Operators, and the C Cystem. C overview recap functions –structured programming –return value is typed –arguments(parameters) pointers.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 3: Introduction to C: Input & Output, Assignments, Math functions.
Khalid Rasheed Shaikh Computer Programming Theory 1.
Prof. Béat Hirsbrunner Ammar Halabi, PhD student (exercises) Dani Rotzetter, Master student (exercises) Bachelor students : Major in computer science (3rd.
CSE 1320 Basics Dr. Sajib Datta
Introduction to C Programming Language. History of C  C was evolved by Dennis Ritchie at AT&T Bell Laboratories in early of 1970s  Successor of: ALGOL.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Unary, Binary, logical Operations, Explicit type conversion Lecture 6 Instructor: Haya Sammaneh.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Introduction to C Programming I Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
From Algorithms to Programs Both are sets of instructions on how to do a task Algorithm: –talking to humans, easy to understand –in plain (English) language.
Arithmetic Expressions
‘C’ Programming Structures and Commands
Beginning the Study of the C Programming Language
The Machine Model Memory
Computer Science 210 Computer Organization
Operators And Expressions
Computer Programming Techniques Semester 1, 1998
Getting Started with C.
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Short Overview Lembit Jürimägi.
Introduction to C Programming Language
Introduction to C Programming
Computer Science 210 Computer Organization
Lexical Elements, Operators, and the C Cystem
Lexical Elements, Operators, and the C Cystem
A First Book of ANSI C Fourth Edition
C Preprocessor(CPP).
Govt. Polytechnic,Dhangar
Introduction to C Topics Compilation Using the gcc Compiler
Assignment Operators Topics Increment and Decrement Operators
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
Assignment Operators Topics Increment and Decrement Operators
B. Ramamurthy University at Buffalo
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Getting started Variables Basic C operators Conditionals
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C EECS May 2019.
C – Programming Language
Programming Languages and Paradigms
Introduction to C Programming
Presentation transcript:

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

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

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.

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

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); }

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

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

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.

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.

C Library Functions: Examples 10

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__)

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

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

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); }

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

Operators 16  Logical Operators: &&AND ||OR !NOT

Control structures 17 Control structures  if,  if-else,  for,  while,  do-while,  switch

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

Precedence and Associativity 19

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

21 l = 4; n = 3; m = 2; x = l * n + m++; After the assignment to x. m 14 3

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);

Precedence and Associativity 23

24 Both are lower in precedence than the arithmetic operators. 10 > > (1 + 12) FALSE 0 Associativity: left to right. int x; x = 100; printf(''%d", (x>10)); __?

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" ); } }

Example 26 See

Answer 27

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

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

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

Example 31 It is also possible to nest ternary

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.

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); }

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 #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 =

Think Idea 36 c = (c > =‘a’ && c < = ‘z’) ? c - (‘z’ - ‘Z’):c;