C Programming Part 2. Digital Design and Computer Architecture. David Money Harris and Sarah L. Harris. Copyright 2011 S. Harris and D.

Similar documents
Informatica e Sistemi in Tempo Reale

Sources: On the Web: Slides will be available on:

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

The C Programming Language course syllabus associate level

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

5 Arrays and Pointers

arrays C Programming Language - Arrays

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CP Lab 2: Writing programs for simple arithmetic problems

Caml Virtual Machine File & data formats Document version: 1.4

Comp151. Definitions & Declarations

/* File: blkcopy.c. size_t n

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

V850E2/ML4 APPLICATION NOTE. Performance Evaluation Software. Abstract. Products. R01AN1228EJ0100 Rev Aug. 24, 2012

An Incomplete C++ Primer. University of Wyoming MA 5310

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

Chapter 7D The Java Virtual Machine

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Embedded C Programming

The C Programming Language

Programming the PIC18/ XC8 Using C- Coding Dr. Farahmand

Lecture 22: C Programming 4 Embedded Systems

The programming language C. sws1 1

How To Write Portable Programs In C

Fundamentals of Programming

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

File Handling. What is a file?

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 13 Storage classes

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Simple C Programs. Goals for this Lecture. Help you learn about:

ELEG3924 Microprocessor Ch.7 Programming In C

C++ Programming Language

Introduction to Java

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

C Interview Questions

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Keil C51 Cross Compiler

ECE 341 Coding Standard

Illustration 1: Diagram of program function and data flow

64-Bit NASM Notes. Invoking 64-Bit NASM

Project 2: Bejeweled

Passing 1D arrays to functions.

Member Functions of the istream Class

Displaying a Numerical Value on HyperTerminal (or equ.)

System Calls Related to File Manipulation

So far we have considered only numeric processing, i.e. processing of numeric data represented

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

DNA Data and Program Representation. Alexandre David

Module 816. File Management in C. M. Campbell 1993 Deakin University

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

Stack Overflows. Mitchell Adair

Chapter 13 - The Preprocessor

ESPResSo Summer School 2012

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

System Calls and Standard I/O

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

CS61: Systems Programing and Machine Organization

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Tutorial on C Language Programming

Arrays in Java. Working with Arrays

Number Representation

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Nemo 96HD/HD+ MODBUS

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Hacking Techniques & Intrusion Detection. Ali Al-Shemery arabnix [at] gmail

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Off-by-One exploitation tutorial

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

LC-3 Assembly Language

Memory Systems. Static Random Access Memory (SRAM) Cell

Object Oriented Software Design II

CSC230 Getting Starting in C. Tyler Bletsch

Servo Motor API nxt_motor_get_count nxt_motor_set_count nxt_motor_set_speed

Crash Course in Java

Draft. v 0.1r THE GEORGE WASHINGTON UNIVERSITY. High Performance Computing Laboratory. UPC Manual

SQLITE C/C++ TUTORIAL

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

Introduction to Python

Interface and Simulation of a LCD Text Display

Intro to GPU computing. Spring 2015 Mark Silberstein, , Technion 1

Java Programming Fundamentals

FEEG Applied Programming 5 - Tutorial Session

13 Classes & Objects with Constructors/Destructors

Application Note. Introduction AN2471/D 3/2003. PC Master Software Communication Protocol Specification

How Compilers Work. by Walter Bright. Digital Mars

Simple Image File Formats

Chapter 5 Functions. Introducing Functions

TivaWare Utilities Library

Programming in C an introduction

Embedded Systems Design Course Applying the mbed microcontroller

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Advanced IBM AIX Heap Exploitation. Tim Shelton V.P. Research & Development HAWK Network Defense, Inc. tshelton@hawkdefense.com

Introduction to Java. CS 3: Computer Programming in Java

Transcription:

C Programming Part 2 Digital Design and Computer Architecture David Money Harris and Sarah L. Harris C<1>

C Chapter :: Topics Function Calls Global vs. Local Variables More Data Types Pointers Arrays Characters and Strings C Standard Libraries Compiler Options Command-Line Arguments C<2>

Functions Function calls enable modularity Like hardware modules, functions are defined by: input, output, operation (what they do) General function definition: return type function_name (type arg1, type arg2){ } // function body what it does return type: output function name: describes what it does arguments: inputs function body: performs operation C<3>

Example Function int sum3(int a, int b, int c) { int result = a+b+c; } return result; return type: int function name: sum3 arguments: int a, int b, int c function body: sums inputs and returns the result C<4>

Function without inputs/outputs Inputs and outputs are not required. For example: void printprompt() { } printf( Please enter a number from 1-3:\n ); printf( \t1: $20\n ); printf( \t2: $40\n ); printf( \t3: $60\n ); Note: could also be written: void printprompt(void)... C<5>

Function Prototypes In C, either the function or its prototype must be declared before the function is used. #include <stdio.h> // function prototypes int sum3(int a, int b, int c); void printprompt(); int main() { } int y = sum3(10, 15, 20); printf( sum3() result: %d\n, y); printprompt(); // functions are defined further down on in code C<6>

Functions Write a function that returns the minimum of 3 integers. Also show how to call the function in your code. C<7>

Functions Write a function that returns the minimum of 3 integers. Also show how to call the function in your code. int min3 (int a, int b, int c) { } int tmpmin = a; if (b < tmpmin) tmpmin = b; if (c < tmpmin) tmpmin = c; return tmpmin; # include <stdio.h> int main ( ) { int y = min3 (4, 3, 2); printf ( min result: %d\n, y); } C<8>

Globally vs. Locally Declared Variables Global variable: declared outside of all functions Accessible by all functions Local variable: declared inside a function Accessible only within function C<9>

Globally vs. Locally Declared Variables // This program uses a global variable to find and print the maximum of 3 numbers int max; // global variable holding the maximum value void findmax(int a, int b, int c) { } int tmpmax = a; // local variable holding the temp max value if (b > tmpmax) { if (c > b) tmpmax = c; else tmpmax = b; } else if (c > tmpmax) tmpmax = c; max = tmpmax; int main(void) { } findmax(4, 3, 7); printf("the maximum number is: %d\n", max); C<10>

More Data Types Pointers: a variable whose value is an address Arrays: collection of similar elements Strings: used for representing text C<11>

Pointers A variable whose value is an address Example: int a = 10; int *b = &a; // b stores the address of a Symbols: int * &a indicates that the variable is a pointer to an int returns the address of a C<12>

Pointers A variable whose value is an address Example: int a = 10; int *b = &a; // b stores the address of a Address (Byte #). 3B 3A 39 38 37 36 35 34 Data 1 byte 00000000 00000000 00000000 00100010 00000000 00000000 00000000 00001010 Variable Name b = 34 a = 10 Memory C<13>

Pointer Example // For concreteness, suppose salary1 is at address 0x40 unsigned long salary1, salary2; // 32-bit numbers unsigned long *ptr; /* a pointer specifying the address of an unsigned long variable */ salary1 = 67500; //assign salary1 to be $67500 = 0x000107AC ptr = &salary1; //assign ptr to be 0x0040, the address of salary1 salary2 = *ptr + 1000; /* dereference ptr to give the contents of address 40 = 67500, then add $1000 and set salary2 to $68500 */ C<14>

Pointer Example Address (Byte.#) 0x4B 0x4A 0x49 0x48 0x47 0x46 0x45 0x44 0x43 0x42 0x41 0x40 Data 0x40 68500 67500 Variable Name ptr salary2 salary1 Address (Byte.#) 0x4B 0x4A 0x49 0x48 0x47 0x46 0x45 0x44 0x43 0x42 0x41 0x40 Data 0x00 0x00 0x00 0x40 0x00 0x01 0x0B 0x94 0x00 0x01 0x07 0xAC Variable Name ptr salary2 salary1 Memory Memory C<15>

Pointers: Passing an input by reference #include <stdio.h> void quadruple(int *a) { *a = *a * 4; } int main() { int x; Console Output x before: 5 x after: 20 x = 5; printf( x before: %d\n, x); quadruple(&x); printf( x after: %d\n, x); } return 0; C<16>

Arrays A collection of similar elements Example: long scores[3]; // a 3-element array of longs This allocates 3 * 4 bytes = 12 bytes. Index goes from 0 to N-1 (N is # of elements) scores[0], scores[1], scores[2] The value of scores is the address of element 0 C<17>

Initializing Arrays At declaration: // scores[0]=93; scores[1]=81; scores[2]=97; long scores[3]={93, 81, 97}; After declaration, 1 element at a time: Individually: scores[0] = 93; scores[1] = 81; scores[2] = 97; Using a for loop: for (i=0; i<3; i++) scores[i] = 100-i; C<18>

Arrays in memory long scores[3]={93, 81, 97}; Address (Byte.#) 0x61 0x60 0x59 0x58 0x57 0x56 0x55 0x54 0x53 0x52 0x51 0x50 Data 97 81 93 Variable Name scores[2] scores[1] scores[0] Address (Byte.#) 0x4B 0x4A 0x49 0x48 0x47 0x46 0x45 0x44 0x43 0x42 0x41 0x40 Data 0x00 0x00 0x00 0x61 0x00 0x00 0x00 0x51 0x00 0x00 0x00 0x5D Variable Name scores[2] scores[1] scores[0] Memory scores is of type long * The value of scores is 0x50 Memory C<19>

Passing an Array into a function #include <stdio.h> int getmean(int *arr, int len); int main() { int data[5] = {78, 14, 99, 27, 16}; } int avg = getmean(data, 5); printf( The average data value was: %d.\n, avg); return 0; int getmean(int *arr, int len) { int i, mean = 0; for (i=0; i < len; i++) mean += arr[i]; mean = mean / len; return mean; } C<20>

Arrays as input arguments The following function prototypes could be used for the getmean() function: int getmean(int *arr, int len); int getmean(int arr[], int len); int getmean(int arr[5], int len); C<21>

Another Array Example short wombats[10]; // array of 10 2-byte quantities // suppose they re stored at 0x20-0x33. short *wombptr; // a pointer to a short wombats[0] = 342; // store 342 in addresses 0x20-21 wombats[1] = 9; // store 9 in addresses 0x22-23 wombptr = &wombats[0]; // wombptr = 0x20 *(wombptr+3) = 7; /* offset of 3 elements, or 6 bytes. Thus addresses 0x26-27 = 7, so this is another way to write wombats[3] = 7. */ C<22>

Strings Strings: used for representing text array of chars last element of string is NULL character \0 Example: char strvar[10] = Hello! ; C<23>

ASCII Codes American Standard Code for Information Interchange C<24>

String Stored in Memory char strvar[10] = Hello! ; Address (Byte.#) 0x5A 0x59 0x58 0x57 0x56 0x55 0x54 0x53 0x52 0x51 0x50 0x4F Data "Hello!" Variable Name str Address (Byte.#) 0x5A 0x59 0x58 0x57 0x56 0x55 0x54 0x53 0x52 0x51 0x50 0x4F Data 0x00 0x21 0x6F 0x6C 0x6C 0x65 0x48 Variable Name str Memory Memory C<25>

Format codes Floating Point Examples: float pi = 3.14159, e = 2.7182, c = 3e8, y = 23444.3; printf("pi = %3.2f\ne = %6.3f\nc = %5.3f \ny = %10.0f\n", pi, e, c, y); Console Output pi = 3.14 e = 2.718 c = 300000000.000 y = 23444 C<26>

Printing Strings char *str = Hello! ; printf( str: %s, str); Console Output str: Hello! C<27>

C Standard Libraries Built-in functions provided by the compiler stdio.h stdlib.h math.h C-<28>

Standard Input/output Library stdio.h Write the following line at the top of your code: #include <stdio.h> Includes functions such as: printf() scanf() C-<29>

printf() int a=4, b=5, c=17, d=14; printf( a = %d, b = %d, c = %d, d = %d\n, a, b, c, d); C-<30>

scanf() int a; char str[80]; float f; printf( Enter an integer.\n );" scanf( %d, &a); printf( Enter a floating point number.\n ); scanf( %f, &f); printf( Enter a string.\n ); scanf( %s, str); // note no & needed: str is a pointer to // the beginning of the array C-<31>

Standard Library stdlib.h Write the following line at the top of your code: #include <stdlib.h> Includes functions such as: rand() srand() C-<32>

rand() #include <stdlib.h> int x, y; x = rand(); // x = a random integer y = rand() % 10; // y = a random number from 0 to 9 C-<33>

srand() #include <stdlib.h> #include <time.h> int main() { int x; srand(time(null)); // seed the random number generator } x = rand() % 10; // random number from 0 to 9 printf("x = %d\n", x); C-<34>

Math Library math.h Write the following line at the top of your code: #include <math.h> #include <stdio.h> #include <math.h> float a, b, c, d, e; a = cos(0); // 1, note: the input argument is in radians b = 2 * acos(0); // pi c = sqrt(144); // 12 d = log10(1000); // 3 e = floor(178.567); // 178, rounds to next lowest whole number printf("a = %f, b = %f, c = %f, d = %f, e = %f\n", a, b, c, d, e); Console Output a = 1.000000, b = 3.141593, c = 12.000000, d = 3.000000, e = 178.000000 C-<35>

Compiler Options C-<36>

Command Line Arguments argc: argument count argv: argument vector #include <stdio.h> int main(int argc, char *argv[]) { int i; } for (i=0; i<argc; i++) printf( argv[%d] = %s\n, i, argv[i]); C-<37>