Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016

Similar documents
CS 261 Data Structures. Introduction to C Programming

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

Technical Questions. Q 1) What are the key features in C programming language?

PRINCIPLES OF OPERATING SYSTEMS

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

EL2310 Scientific Programming

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

CS201- Introduction to Programming Current Quizzes

Dynamic Memory Allocation

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

Problem Solving and 'C' Programming

Kurt Schmidt. October 30, 2018

CS 61C: Great Ideas in Computer Architecture Introduction to C

CSCI 171 Chapter Outlines

The output will be: marks all or nothing. 1 #include <stdio.h> 2 main() { 3 int i; int j; 4 int *p; int *q; 6 p = &i; 7 q = &j; 8 i = 1;

More about BOOLEAN issues

Fundamental of Programming (C)

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

Fundamentals of Programming

Slide Set 5. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Programming for Engineers C Preprocessor


Lecture 2: C Programm

Lectures 5-6: Introduction to C

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

EM108 Software Development for Engineers

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

PROGRAMMAZIONE I A.A. 2017/2018

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Informatica e Sistemi in Tempo Reale

SYSC 2006 C Winter 2012

CS61, Fall 2012 Section 2 Notes

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Advanced Pointer Topics

CS C Primer. Tyler Szepesi. January 16, 2013

Lecture 9 Assertions and Error Handling CS240

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

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

Lectures 5-6: Introduction to C


Have examined process Creating program Have developed program Written in C Source code

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Chapter IV Introduction to C for Java programmers

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Multiple Choice Questions ( 1 mark)

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

edunepal_info

Exercise Session 2 Simon Gerber

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

4) In C, if you pass an array as an argument to a function, what actually gets passed?

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Compiling and Running a C Program in Unix

Model Viva Questions for Programming in C lab

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

A Crash Course in C. Steven Reeves

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

ME 461 C review Session Fall 2009 S. Keres

Online Judge and C. Roy Chan. January 12, Outline Information Online Judge Introduction to C. CSC2100B Data Structures Tutorial 1

Computer Programming. The greatest gift you can give another is the purity of your attention. Richard Moss

The Preprocessor. CS 2022: Introduction to C. Instructor: Hussam Abu-Libdeh. Cornell University (based on slides by Saikat Guha) Fall 2011, Lecture 9

Introduction to the C Programming Language

Understanding Pointers


Signals, Instruments, and Systems W2. C Programming (continued)

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

COMP322 - Introduction to C++

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

THE UNIVERSITY OF WESTERN ONTARIO. COMPUTER SCIENCE 211a FINAL EXAMINATION 17 DECEMBER HOURS

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Recitation #11 Malloc Lab. November 7th, 2017

Variation of Pointers

Modifiers. int foo(int x) { static int y=0; /* value of y is saved */ y = x + y + 7; /* across invocations of foo */ return y; }

Dynamic Allocation in C

Homework #3 CS2255 Fall 2012

C Programming Review CSC 4320/6320

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 C: Linked list, casts, the rest of the preprocessor (Thanks to Hal Perkins)

Final CSE 131B Spring 2004

Advanced C Programming and Introduction to Data Structures

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Friday, February 10, Lab Notes

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

What is an algorithm?

Contents. A Review of C language. Visual C Visual C++ 6.0

POINTER & REFERENCE VARIABLES

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

The C Programming Language Guide for the Robot Course work Module

CS 314 Principles of Programming Languages. Lecture 11

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Lecture 2. Xiaoguang Wang. January 16th, 2014 STAT 598W. (STAT 598W) Lecture 2 1 / 41

Transcription:

Oregon State University School of Electrical Engineering and Computer Science CS 261 Recitation 2 Spring 2016

Outline Programming in C o Headers o Structures o Preprocessor o Pointers Programming Assignment 1 CS 261 Data Structures 2

Programming in C Headers To include a standard library in C, use <>. E.g: #include <stdio.h> To include a header file, use quotation marks. E.g: #include sort.h In fact, when using angle brackets, the preprocessor only searches for it in certain directories. When using quotation marks, the preprocessor first looks for the file in the current working directory. CS 261 Data Structures 3

Programming in C Special operators: `++` and `--` operators `++`: x is incremented (x=x+1) Ø ++x : increments x before it is evaluated Ø x++ : increments xafter it is evaluated `--` : x is decremented (x=x-1) Ø --x : decrements x before it is evaluated Ø x-- : decrements x after it is evaluated Usually best to use x++ or x-- CS 261 Data Structures 4

Programming in C The `struct` type: Like class in Java with no method. Declare a struct data type: struct student /*student is the name of this struct*/ { char name[40]; int id; double gpa; }; Declare variables with the structure type: struct student a1, a2; struct student *pointer_to_a1; struct student entireclass[100]; CS 261 Data Structures 5

Programming in C Initialize structure variables: struct article {char name[15]; char color[14]; double price;}; struct article flower= { rose, green, 2.49}; struct article bouquet[10] ; bouquet [0] = flower; struct article *particle = (struct article *) malloc (sizeof(struct article)); CS 261 Data Structures 6

Programming in C Access structure members: Using the dot operator flower.name // The array 'name' flower.price // The double variable 'price' Using pointers particle = &flower; // Let particle point to flower particle->color // Access members of flower particle->price // using the pointer particle CS 261 Data Structures 7

Programming in C C Preprocessor The C compiler preprocesses every source file before performing the actual translation. The preprocessor removes comments and replaces macros with their definitions. Every preprocessing directive appears on a line by itself. If the directive is long, it can be continued on the next line by inserting a backslash (\) as the last character before the line break. `#define` directive: Used to define macros Syntax: #define name [replacement_text] Example: #define BUF_SIZE 512 // Symbolic constant #define MAX(a,b) ((a) > (b)? (a) : (b)) CS 261 Data Structures 8

Programming in C #ifdef and #ifndef The #ifdef and #ifndef directives are used to test if a certain directive has been defined or not defined respectively. Syntax #ifdef _WIN32 //Compiling under a windows environment... #endif #ifndef _WIN32... #endif Whats the difference between if and ifdef? CS 261 Data Structures 9

Pointers A pointer represents the address and type of a variable or a function. In other words, for a variable x, &x is a pointer to x. Two fundamental operators: &: address-of operator to get a pointer to (address of) a variable *: dereference operator - get the thing the pointer points to. * is also used to declare a pointer variable int i=5, int *p; Note: The name of an array is automatically converted to a pointer to the array's first element. The value of a null pointer is 0. CS 261 Data Structures 10

Why pointers A simple explanation found on Web To impress friends *wink* Pointers can give performance gains New data structure possibilities CS 261 Data Structures 11

Pointer arithmetic Two arithmetic operations can be performed on pointers: An integer can be added to or subtracted from a pointer. One pointer can be subtracted from another of the same type. In arithmetic operations on pointers, the size of the objects pointed to is automatically taken into account. int a[3] = { 0, 10, 20 }; int *ptr_a = a; &a[i], a+i, ptr_a+i printf( %d, // An array with &a[2]); three //Ans elements : memory location // Let ptr_a pointed by to 20 a[0] // pointers to the i-th array element a[i], *(a+i), *(ptr_a+i), ptr_a[i] // the i-th array element ptr_a = a+2; printf( %d, // Let pa *(a+1); point to //Ans a[2] : 10 int n = ptr_a - a; // n = 2 CS 261 Data Structures 12

More on pointers! 13

Pointer Value vs. Thing Pointed At the value of the pointer vs. the value of the thing the pointer points to: Pointer pval D3C2 *pval Value at location D3C2 42 14

Pointers int *pval; /* Pointer uninitialized to unallocated integer value. */ pval Pointer? 15

Pointers int *pval; /* Pointer uninitialized to unallocated integer value. */ pval = 0; /* Initialize pointer to indicate that it is not allocated. */ Pointer pval Indicates a null pointer. 16

Pointers int *pval; /* Pointer uninitialized to unallocated integer value. */ pval = 0;... /* Initialize pointer to indicate that it is not allocated. */ pval Pointer /* Allocate integer and */ /* assign memory address to pval. */ Value??? pval = (int *) malloc(sizeof(int)); 17

Pointers int *pval; /* Pointer uninitialized to unallocated integer value. */ pval = 0;... /* Initialize pointer to indicate that it is not allocated. */ /* Allocate integer and */ /* assign memory address to pval. */ pval = (int *) malloc(sizeof(int)); *pval = 42; pval Pointer Value 42 18

Pointer Syntax Use * to declare a pointer, get value of pointer Use & to get address of a variable double *ptr; double pi, e; 19

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; &pi printf("values: %p %g %g %g\n", ptr, *ptr, pi, e); e??.??? ptr pi??.??? 20

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; &pi printf("values: %p %g %g %g\n", ptr, *ptr, pi, e); e??.??? ptr pi 3.14159 21

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; printf("values: %p %g %g %g\n", ptr, *ptr, pi, e); &e e??.??? ptr pi 3.14159 22

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; printf("values: %p %g %g %g\n", ptr, *ptr, pi, e); &e e 2.71828 ptr pi 3.14159 23

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; &e ptr pi 3.14159 e 2.71828 printf("%p %g %g %g\n", ptr, *ptr, pi, e); Output:? 24

Pointer Syntax double *ptr; double pi, e; ptr = π *ptr = 3.14159; ptr = &e; *ptr = 2.71828; &e ptr pi 3.14159 e 2.71828 printf("%p %g %g %g\n", ptr, *ptr, pi, e); Output: ffbff958 2.71828 3.14159 2.71828 25

Alternative Pointer Syntax Use [] to declare a pointer Use [0] to get the value of pointer double data[]; /*pointer*/ double value = 5.3; /*variable*/ data = & value; printf("%g",data[0]); Output:? 26

CS 261 Data Structures

Programming Assignment 1 Helpful Hints warning: implicit declaration of function Probable reason: Function prototype not declared Fix: 2 choices Insert the function prototype before the main function in C Use a header file (myfunction.h) to declare the function prototype and include this header file in main.c <filename>.h: No such file or directory Probable reason: wrong include definition warning: implicit declaration of function `malloc ( free ) or assert Probable reason: stdlib.h or assert.h library not included Fix: To call `malloc` and `free` functions, you need to include stdlib.h library at the beginning of source files. To call assert function, you need to include assert.h. CS 261 Data Structures 28

Programming Assignment 1 Helpful Hints Even after a successful compilation, I'm not allowed to execute the program - Example: % gcc main.c sort.c -o myprog % myprog Error message: myprog: Too few arguments. Reason: Path to the executable file not provided. Executable file name is a UNIX keyword like cat, grep, Fix: provide the path to the executable file:./myprog We can provide full path to the file, or just use `./` to indicate the current directory CS 261 Data Structures 29

Programming Assignment 1 Helpful Hints CodeBlocks errors: Message: Linking stage skipped (build target has no object files to link) Fix: The source file must belong in `debug` and release` targets in order to be compiled. CS 261 Data Structures 30

CS 261 Data Structures

Test Assignment Solution Question: - Code in C for printing prime numbers in an infinite loop. - Execution is stopped by the user - Comments based on guidelines Helper function: int isprime(int n) { for(int i = 2; i * i <= n; i++) { /* for every possible number i */ if (n % i == 0) return 0; /* if i divides n then n is not a prime number */ } return 1; /* if no number divides n from 2 to sqrt(n), n is prime */ } CS 261 Data Structures 32

Test Assignment Solution Question: - Code in C for printing prime numbers in an infinite loop. - Execution is stopped by the user - Comments based on guidelines Main function: int main() { int j = 2; /* first prime number */ printf("press enter for next prime number, give other character for termination\n"); while(true) { if (isprime(j)){ /* if j is a prime number */ printf("%d is prime",j); /* then print it */ char c = getchar(); if (c!= '\n') /* if the user did not press enter alone */ return 0; /* then break out of the loop by returning */ } j++; /* increase j to the next integer value */ } return 0; /* purely cosmetic reasons, never executed */ } CS 261 Data Structures 33

More Questions? CS 261 Data Structures