F28PL1 Programming Languages Lecture 6: Programming in C - 1.

Slides:



Advertisements
Similar presentations
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Basic C Programming Data Types and Arithmetic Operations 01/30/15.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Data types and variables
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 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.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Chapter 2 Data Types, Declarations, and Displays
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
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.
Computer Science 210 Computer Organization Introduction to C.
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
F28PL1 Programming Languages Lecture 7 Programming in C - 2.
Chapter 11 Programming in C Compilation vs. Interpretation Different ways of translating high-level language Compilation translates code into machine.
 Input and Output Functions Input and Output Functions  OperatorsOperators Arithmetic Operators Assignment Operators Relational Operators Logical Operators.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Introduction to Programming
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
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.
Department of Electronic & Electrical Engineering Lecture 3 IO reading and writing variables scanf printf format strings "%d %c %f" Expressions operators.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
F28HS2 Hardware-Software Interface Lecture 1: Programming in C 1.
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.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Numbers in ‘C’ Two general categories: Integers Floats
The Machine Model Memory
Computer Science 210 Computer Organization
Tokens in C Keywords Identifiers Constants
ITEC113 Algorithms and Programming Techniques
Computer Science 210 Computer Organization
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Introduction to C Topics Compilation Using the gcc Compiler
Lectures on Numerical Methods
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Differences between Java and C
C Programming Getting started Variables Basic C operators Conditionals
WEEK-2.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 11 Programming in C
Introduction to C EECS May 2019.
Module 2 Variables, Data Types and Arithmetic
Programming Languages and Paradigms
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
Presentation transcript:

F28PL1 Programming Languages Lecture 6: Programming in C - 1

Overview strict, strongly typed, imperative system programming language combines high-level constructs with low level access to type representations and memory Reference: B. Kernighan & D. Ritchie, The C Programming Language (2 nd Ed), Prentice-Hall, 1988

Overview C looks like Java BUT IS VERY DIFFERENT! Java has high-level objects C exposes low-level memory formats & addresses must manage memory explicitly very easy to make programming errors – almost invariably address errors

Running C programs suppose $ is Linux prompt put program text in name 1.c $ gcc –o name 2 name 1.c compile name 1.c using GNU C compiler and put executable in name 2 $ name 2 run compiled program in name 2 $ name 2 arg 1 … arg N run name 2 with command line args arg 1 … arg N

Running C programs $ gcc … -O … generate optimised code $ gcc –c name 1.c … name N.c generate object files name 1.o … name N.o only $ gcc –o name name 1.o … name N.o link object files name 1.o … name N.o and put executable in name

Running C programs $ gcc name.c forgot –o name ? puts executable in a.out ! $ man gcc Linux manual entry for GNU C compiler can use cc instead of gcc – proprietary C compiler for host OS/platform

Program layout 1.#include... 2.#define... 3.extern... 4.declarations 5.function declarations 6.main(int argc,char ** argv) 7.{... }

Program layout 1. include files – #include “...” == look in current directory – #include == look in system directories – import libraries via header files: name.h e.g. for I/O 1.#include... 2.#define... 3.extern... 4.declarations 5.function declarations 6.main(int argc, 7. char ** argv) 8.{... }

Program layout 2. macro and constant definitions 3. names/types of variables/functions used in this file but declared in linked files 1.#include... 2.#define... 3.extern... 4.declarations 5.function declarations 6.main(int argc, 7. char ** argv) 8.{... }

Program layout 4. & 5. declare all variables before all functions 6. & 7. main function with optional command line argument count and array declarations and statements terminated with a ; 1.#include... 2.#define... 3.extern... 4.declarations 5.function declarations 6.main(int argc, 7. char ** argv) 8.{... }

Display output 1 printf(“ text” ) system function sends text to the display \n == newline \t == tab

Display output 1 e.g. hello.c #include main(int argc,char ** argv) { printf("hello\n"); }... $ gcc -o hello hello.c $ hello hello $

Memory organisation stack – allocated automatically – global declarations – local declarations – function parameters heap – allocated by program – c.f. Java new – no garbage collection stack heap top of stack top of heap memory

Declarations type name; allocates space for new variable of type called name on stack name letters + digits + _ starting with a letter C convention – lower case = variable name – UPPER CASE = symbolic constant

Declarations can group declarations for same type type name 1 ; type name 2 ;... type name N ;  type name 1,name 2...name N ;

Declarations basic types – char – character – int – integer – short – short integer – long – long integer – float – floating point number – double – double size floating point number

Declarations amount of space for type depends on – type – platform – compiler measure type sizes in 8 bit bytes int sizeof( type ) returns number of bytes for type

Display output 2 printf(“ format ”, exp 1...exp N ) displays the values of expressions exp 1...exp N depending on the format characters %d == decimal integer %f == floating point %x == hexadecimal %s == string

Display output 2 NB variable number of arguments must have one format for each argument any non-format information in string is displayed as text

Sizes of types e.g. typesize.c #include main(int argc,char ** argv) { printf("char: %d\n",sizeof(char)); printf("int: %d\n",sizeof(int)); printf("short: %d\n",sizeof(short)); printf("long: %d\n",sizeof(long)); printf("float: %d\n",sizeof(float)); printf("double: %d\n", sizeof(double)); }

Sizes of types on 64 bit PC Linux $ gcc -o typesize typesize.c $ typesize char: 1 int: 4 short: 2 long: 4 float: 4 double: 8

Hexadecimal byte sequences may be described in hexadecimal 0X h 1 h 2...h N where h i == 0..9 A..F digitbinarydigitbinary A B C D E F1111

Memory allocation to values 2 digits == 8 bits == 1 byte NB values stored from most significant to least significant byte e.g. int a; a = 0x ; a byte

Address operator: & declaration: type name associates name with address of enough memory for type & name address of 1 st byte allocated to variable name lvalue on PC Linux: address4 bytes

Memory allocation to declarations e.g. addrs.c #include main(int argc,char ** argv) { int a,b,c; double x,y,z; printf("&a: %x, &b: %x, &c: %x\n", &a,&b,&c); printf("&x: %x, &y: %x, &z: %x\n", &x,&y,&z); }... $ addrs &a: bfe5118c, &b: bfe51188, &c: bfe51184 &x: bfe51178, &y: bfe51170, &z: bfe51168

Memory allocation to declarations a: bfe5118c b: bfe51188 c: bfe51184 x: bfe51178 y: bfe51170 z: bfe x x 8c-88 == == == 12 == 8+4? -64 bit machine -padding to 8 byte boundary == == 8

Expressions constant  value of constant name  value from memory – NB value may differ depending on what type context name is used in unary/binary expression function call – NB C function == Java method

Constants signed integer – e.g signed decimal – e.g – e.g E11 == * character: ‘ letter ’ e.g. ‘a’ ‘\n’

Operator expressions unary op exp – evaluate exp – apply op to value binary infix exp 1 op exp 2 – evaluate exp 1 – evaluate exp 2 – apply op to values

Arithmetic unary minus: - binary infix + == add - == subtract * == multiply / == division % == integer modulo/remainder

Arithmetic (...) – brackets precedence (...) before... unary – before... * or / or % before... + or – before... function call

Arithmetic expressions evaluated from left to right BUT compiler may rearrange + and * for efficiency e.g. A+B*C  LOAD R1,A LOAD R2,B MULT R2,C ADD R1,R2 e.g. B*C+A  LOAD R1,B MULT R1,C ADD R1,A NB not ARM assembler

Arithmetic mixed mode arithmetic permitted always works at maximum precision needed for a binary operator: – char & short converted to int – float always converted to double – either operand is double then the other is converted to double – either operand is long then the other is converetd to long

Function call function called as: name ( exp 1...exp N ) evaluate actual parameters exp 1 to exp N – pushing values onto stack function will access formal parameters via stack result of function execution is returned

Keyboard input int scanf(“ format ”, addr 1...addr N ) inputs from keyboard to memory at specified addresses – depending on format characters typically, addr i is & name i i.e. address associated with variable name i int return value for success or end of input or failure

evaluate AX 2 +BX+C #include main(int argc,char ** argv) { int a,b,c,x; printf("a: "); scanf("%d",&a); printf("b: "); scanf("%d",&b); printf("c: "); scanf("%d",&c); printf("x: "); scanf("%d",&x); printf("%d\n",a*x*x+b*x+c); } Example: polynomial evaluation $ poly a: 3 b: 8 c: 4 x: 6 160

evaluate AX 2 +BX+C #include main(int argc,char ** argv) { int a,b,c,x; printf("a: "); scanf("%d",&a); printf("b: "); scanf("%d",&b); printf("c: "); scanf("%d",&c); printf("x: "); scanf("%d",&x); printf("%d\n",a*x*x+b*x+c); } Example: polynomial evaluation $ poly a: 3 b: 8 c: 4 x: put value at address in memory for variable

Indirection operator: * * expression  – evaluate expression to integer – use integer as address to get value from memory so name in expression  *(& name ) 1.get address associated with name 2.get value from memory at that address

Assignment expression 1 = expression 2 ; evaluate expression 1 to give an address – lvalue – on left of assignment evaluate expression 2 to give a value – rvalue – on right of assignment put the value in memory at the address

Assignment assignments are expressions returns the value of expression 2 value ignored when assignment used as a statement

Logic and logical operators no boolean values 0  false any other value  true unary ! - not binary && - logical AND || - logical OR

Comparison operators binary == - equality != - inequality < - less than <= - less than or equal > - greater than >= - greater than or equal

Precedence (...) before && before || before ! before comparison before arithmetic before function call

Block { declarations statements } declarations are optional space allocated to declarations – on stack – for life of block

Iteration: while while( expression ) statement  1.evaluate expression 2.if non-zero then i.execute statement ii.repeat from 1. 3.if zero then end iteration break in statement ends enclosing iteration

Example: sum and average sumav.c include main(int argc,char ** argv) { int count; int sum; int n; count = 0; sum = 0;

Example: sum and average printf("next> "); scanf("%d",&n); while(n!=0) { count = count+1; sum = sum+n; printf("next> "); scanf("%d",&n); } printf("count: %d, sum: %d, average: %d\n",count,sum,sum/count); }

Example: sum and average $ sumav next> 1 next> 2 next> 3 next> 4 next> 5 next> 0 count: 5, sum: 15, average: 3

Iteration: for for( exp 1 ; exp 2 ; exp 3 ) statement  exp 1 ; while( exp 2 ) { statement exp 3 ; } 1.execute statement exp 1 2.repeatedly test exp 2 3.each time exp 2 is true 1.execute statement 2.execute statement exp3 all exps and statement are optional

Iteration: for for( exp 1 ; exp 2 ; exp 3 ) statement usually: – exp 1 initialises loop control variable – exp 2 checks if termination condition met for control variable – exp 3 changes control variable NB must declare control variable before for

Condition: if if( expression ) statement 1 else statement 2  1.evaluate expression 2.if non-zero then execute statement 1 3.if zero then execute statement 2 else statement 2 is optional – if expression is zero then go on to next statement