Storage class and Scope:

Similar documents
Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

ET156 Introduction to C Programming

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

BSM540 Basics of C Language

Fundamental of Programming (C)

A Fast Review of C Essentials Part I

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

C: How to Program. Week /Mar/05

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

ECE 15B COMPUTER ORGANIZATION

Chapter 2 - Introduction to C Programming

Fundamentals of Programming


CGS 3460 Summer 07 Midterm Exam

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

BSM540 Basics of C Language

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

BLM2031 Structured Programming. Zeyneb KURT

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Review of the C Programming Language for Principles of Operating Systems

Procedures, Parameters, Values and Variables. Steven R. Bagley

C Program Development and Debugging under Unix SEEM 3460

Chapter 1 & 2 Introduction to C Language

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

First of all, it is a variable, just like other variables you studied

CS 0449 Sample Midterm

Lectures 5-6: Introduction to C

COP 3275: Chapter 02. Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Chapter 2: Overview of C. Problem Solving & Program Design in C

C Programming Review CSC 4320/6320

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Algorithms & Programming. Midterm Examination # 2. Student Name: Student ID Number: Duration of examination:

CS24 Week 2 Lecture 1

INTRODUCTION 1 AND REVIEW

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

PROGRAMMAZIONE I A.A. 2018/2019

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Basic Types and Formatted I/O

C Syntax Out: 15 September, 1995

Variation of Pointers

Programming and Data Structures

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Tokens, Expressions and Control Structures

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Tutorial 6. Memory Addresses and Pointers. scanf() function. Perils of Pointers. Function Pointers. Declarations vs. Definitions

C Language, Token, Keywords, Constant, variable

Lecture 02 C FUNDAMENTALS

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Fundamental of Programming (C)

Programming Fundamentals (CS-302 )

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

Programming in C++ 4. The lexical basis of C++

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

M1-R4: Programing and Problem Solving using C (JAN 2019)

More on C programming

... Lecture 12. Pointers

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

Introduction to Computing Lecture 01: Introduction to C

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Procedural programming with C

Week 3 Lecture 2. Types Constants and Variables

Character Strings. String-copy Example

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Review of the C Programming Language

C-LANGUAGE CURRICULAM

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

UNIT-I Fundamental Notations

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

MIDTERM TEST EESC 2031 Software Tools June 13, Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Transcription:

Algorithm = Logic + Control + Data Data structures and algorithms Data structures = Ways of systematically arranging information, both abstractly and concretely Algorithms = Methods for constructing, searching, and operating on data structures Characterizing Costs (as a function of input size) Space Time Applications What s a good data structure/algorithm for a particular problem? int v = 0; /* declared at some place in your program */ What can you see from the declaration? storage class : auto, register, static, extern type : value domain value : current value value domain name : symbolic identifier location : memory address size : how many bytes it occupies scope : where it can be accessed Introduction 1 Introduction 2 Storage class and Scope: Auto: declared inside a block, exists only when the block is entered and disappears when execution leaves the block. { int x, y; x and y alive Accessable in this block Static: accessible in the block where it is declared, exists and retains its value in whole program cycle. int x = 0; printf( %d\n, x++); int main(){ static int x = 0; printf( %d\n, x++); int main(){ f(); // 1 f(); // 2 Introduction 3 Introduction 4 Extern: accessible and exists in whole program file and program cycle. Define a global variable exactly once and use external declarations everywhere. /* f1.c */ /* f2.c */ Register: frequently used variables for efficiency purpose. Restrictions: (1) can not take the address of a register variable, (2) can not declare global register variables, (3) a register variable must fit into a single machine word, (4) the compiler may ignore register declaration. int x; void g(){ extern int x; void h(){ /* search the given table to find the given key; return the index if found or 1 otherwise */ int table_search(int a[], register int n, register int key){ register int j; for (j = 0; j < n && a[j]!= key; j++); return (j!= n)? j : -1; Introduction 5 Introduction 6 1

Review of Declaration: Constants:? #define ONE 1? #define TEN 10 #define INPUT_MODE 1 #define BUFSIZE 20 Name: Use descriptive names for global vars, short name for local vars. Be consistent when naming functions, types, variables, and constants.? for (theelementindex = 0; theelementindex < numberofelements; theelementindex++) elementarray[theelementindex] = 0; for (i = 0; i < n; i++) a[i] = 0; Introduction 7 Introduction 8 Do not use id s that contains two or more underscores in a row. Do not use id s that begin with an underscore. int i j = 11; // illegal int m = 20; // illegal int _k = 10; // not recommended Do not change a loop variable inside a for loop block. Update loop variables close to where the loop condition is specified. All flow control primitives (if,, while, for, do, switch, and case) should be followed by a block, even if it is empty. Statements following a case label should be terminated by a statement that exits the switch statement. All switch statements should have a default case. Use break and continue instead of goto. Do not have overly complex functions. Indent to show program structure (better readability). Parenthesize to resolve ambiguity. Introduction 9 Introduction 10? for (j = 0; j < n; j++){ a[j] = j; for (k = j ; k < n; k++){ if (a[j] < 5) a[k] = a[j]; a[k] = k; for (j = 0; j < n; j++){ a[j] = j; for (k = j ; k < n; k++){ if (a[j] < 5) a[k] = a[j]; a[k] = k;? Leapyear = y % 4 == 0 && y % 100! = 0 y % 400 == 0; Leapyear = ((y % 4 == 0) && (y % 100!= 0 ) ) (y % 400 == 0); Be careful with side effects. Operators like ++ have side effects: besides returning a value, they also modify an underlying variable. Side effects can be extremely convenient, but they can also cause trouble because the actions of retrieving the value and updating the variable might not happen at the same time. In C the order of execution of side effects is undefined.? str[j++] = str[j++] = a ; str[j++] = a ; str[j++] = a ;? a[j++] = j;? scanf( %d%d, &x, &a[x]); Introduction 11 Introduction 12 2

Break up complex expressions:? *x += (*xp = (2 * k < (n m)? c[k+1] : d[k--])); if (2 * k < n m) *xp = c[k+1]; *xp = d[k--]; *x += *xp;? child = (!LC &&!RC)? 0 : (!LC? RC : LC); if (LC == 0 && RC == 0) child = 0; if (LC == 0) child = RC; child = LC; Introduction 13 Common usage for consistency:? j = 0; while (j <= n 1) a[j++] = 1;? for ( j = 0; j < n; ) a[j++] = 1;? for ( j = n; --j >= 0; ) a[j] = 1; /* common usage in C */ for (j = 0; j < n; j++) a[j] = 1; /* standard loop for walking along a list */ for (p = list; p!= NULL; p = p->next) Introduction 14 Problem with function-like macros: #define isupper(c) ((c) >= A && (c) <= Z )? while (isupper( c = getchar())) /* error */ while ( (c = getchar()!= EOF && isupper(c )) #define round(x) ((int) ((x) + (((x) > 0)? 0.5 : -0.5))) Number 0:? char *str = 0;? name[n-1] = 0;? double x = 0; /* reserve 0 for a literal integer zero */ char *str = NULL; name[n-1] = \0 ; double x = 0.0;? size = round(sqrt(dx*dx + dy*dy)); /* not an error, but low performance */ Introduction 15 Introduction 16 Debugging: Bug: A defect or fault in a machine, plan, or the like. Oxford English Dictionary (1) do not blame your computer (2) do not blame your compiler (3) do not blame the standard library experienced programmers know that, realistically, most problems are their own fault. Use debugger, or Write self-checking code: void check(char* s){ printf( %s\n, s); fflush(stdout); abort(); Usage: check( ); // suspect code check( ); // before suspect // after suspect Introduction 17 Introduction 18 3

Review of pointer: int x = 4; int *a = &x; int **b = &a; b: &a a: &x a: &x x 4 a addr(x) b addr(a) &x addr(x) &a addr(a) &b addr(b) *x illegal *a 4 *b addr(x) *(&x) 4 **a illegal **b 4 *b == a == &x **b == *a == x ***b illegal Relationship of -> and. : typedef struct { char name[20]; int grade; student; student s; student *sp = &s; s.grade = 97; sp -> grade = 97; (*sp).grade = 97; (&s) -> grade = 97; // direct structure field selection // indirect structure field selection // (*sp).grade == sp->grade // s.grade == (&s)->grade Introduction 19 Introduction 20 Structures and Operators: sizeof operator determines the number of bytes used by a structure. sizeof(s) // using a student variable sizeof(student) // or using a type Don t assume the size of a structure is the sum of the size of its fields. sizeof(s.name) + sizeof(s.grade) sizeof(s) Structures and Operators: Assignment operator = applies to structures which copies the contents of one structure into another. student new_student = s; No operators for comparing structures. (new_student == s) // wrong Introduction 21 Introduction 22 Self-test: For the following multiple choice questions circle all the answers for each question that are correct. (1) Lifetime of a variable is defined by its a) data type b) storage class c) name d) memory address Introduction 23 (2) If a local variable has the same name as a global variable, what will happen? a) A compiler error gets generated. b) Both variables will share the same memory location. c) The local variable will supersede the global variable, i.e. hide it. d) Both are visible to the entire program. (3) Given the declaration, which scanf would successfully read in a float value into x? float x, *y = &x, **z = &y; a) scanf("%f", &x); b) scanf("%f", *y); c) scanf("%f", *z); d) scanf("%f", y); Introduction 24 4

(4) Address of an array declared as int x[10] is indicated by a) *(&x) b) &x[0] c) &(*x) d) none of the above (5) What would be the value of t after the following code executes? int t = 0; char *s = "Hello world!"; char *u = s + 2; for ( ; *u; ++u, ++t); a) 10 b) 12 c) 13 d) none of the above (6) What is the definition of or concept behind unions? a) They allow you to put two things in the same place at the same time. b) They allow the same memory location to be accessed using different identifiers. c) They allow merging of different structures. d) They are identical to structures. (7) Given the following expression which of the following is not true? s[3].x[0]->t a) s is an array. b) x[0] is a pointer to a structure. c) t is a member of s[3]. d) x is a member of s[3]. Introduction 25 Introduction 26 (8) Text files are nice because they a) are more efficient than binary files. b) are portable among different platforms. c) take up less space than binary files, typically. d) can be accessed randomly. (9) Given that x is an unsigned char, x 0xFF will always give a) all zeros b) all ones c) x d) none of the above Introduction 27 Using the following declaration for each question, identify the output for each part. int x = 20, y = 5, *px = &x, *py; int a[]={2, 4, 8, 1, 5, 3, *pa = a; a) printf("%d", (*px) + 3); b) py = px; *py += *px*y; printf("%d\n", x); c) printf("%d\n", *(pa + 3)); d) pa++; printf("%d\n", *pa + 3); Introduction 28 Trace the program and give the output #include <stdio.h> int main(void){ char s[] = bskbmshd"; int i = 0; while(s[i]){ if (s[i] < 'f') s[i++] -= 1; s[i++] += 1; printf("the resulting string is %s.\n", s); return 0; Introduction 29 5