Programming in C First meeting Tiina Niklander

Similar documents
Programming in C First meeting

Programming in C week 1 meeting Tiina Niklander

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

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

PRINCIPLES OF OPERATING SYSTEMS

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

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

CSE 124 Discussion (10/3) C/C++ Basics

Programming in C Lecture Tiina Niklander

CS 253: Intro to Systems Programming 1/21

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

CS240: Programming in C

Software Development With Emacs: The Edit-Compile-Debug Cycle

Lectures 5-6: Introduction to C

Short Notes of CS201

Lectures 5-6: Introduction to C

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

CS201 - Introduction to Programming Glossary By

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

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

The C standard library

CSE 351. Introduction & Course Tools

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

Lecture 07 Debugging Programs with GDB

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

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

Lecture 03 Bits, Bytes and Data Types

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

SU 2017 May 18/23 LAB 3 Bitwise operations, Program structures, Functions (pass-by-value), local vs. global variables. Debuggers

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

C introduction: part 1

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

Recitation: Cache Lab & C

Programming in C. What is C?... What is C?

Reviewing gcc, make, gdb, and Linux Editors 1

CSCI 2132 Final Exam Solutions

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

CSE 374 Programming Concepts & Tools

just a ((somewhat) safer) dialect.

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

CSCI 171 Chapter Outlines

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Intermediate Programming, Spring 2017*

12. Debugging. Overview. COMP1917: Computing 1. Developing Programs. The Programming Cycle. Programming cycle. Do-it-yourself debugging

COSC Software Engineering. Lecture 16: Managing Memory Managers

Problem Set 1: Unix Commands 1

How to learn C? CSCI [4 6]730: A C Refresher or Introduction. Diving In: A Simple C Program 1-hello-word.c

CS133 C Programming. Instructor: Jialiang Lu Office: Information Center 703

CMPT 300. Operating Systems. Brief Intro to UNIX and C

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

CSE 303: Concepts and Tools for Software Development

High Performance Computing MPI and C-Language Seminars 2009

Laboratory 1 Semester 1 11/12

Exercise 1: Basic Tools

High-performance computing and programming I. Introduction to C programming in *NIX

CS61, Fall 2012 Section 2 Notes

Class Information ANNOUCEMENTS

Continue: How do I learn C? C Primer Continued (Makefiles, debugging, and more ) Last Time: A Simple(st) C Program 1-hello-world.c!

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

EL2310 Scientific Programming

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Friday, September 16, Lab Notes. Command line arguments More pre-processor options Programs: Finish Program 1, begin Program 2 due next week

Understanding Pointers

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

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

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

Midterm Review (overview of fall 2005 midterm)" Jennifer Rexford!

C & Data Structures syllabus

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Faculty of Science Final Examination. Computer Science B Introduction to Software Systems

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

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

CS2141 Software Development using C/C++ Debugging

EL2310 Scientific Programming

OBJECT ORIENTED PROGRAMMING

Programming Tips for CS758/858

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Formal Methods for C

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

CIS 190: C/C++ Programming. Lecture 2 Pointers and More

CS240: Programming in C. Lecture 2: Overview

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins)

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

Introduction to Programming Systems

CSE 333 Midterm Exam 7/29/13

CSE 303 Concepts and Tools for Software Development. Magdalena Balazinska Winter 2010 Lecture 27 Final Exam Revision

C programming basics T3-1 -

edunepal_info

Embedded Software TI2726 B. 3. C tools. Koen Langendoen. Embedded Software Group

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

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Transcription:

Programming in C First meeting 5.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 1

Learning goal objectives Language structures, data structures, modules, functions+parameters Files Pointers, structured elements Using properly dynamic and static data structures like tables, lists, queues, stacks, trees (from data structures and algorithms course!) NOTE: No C++ features allowed in exam. pure ANSI C only Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 2

Course structure No weekly exercise deadlines, but goal is to do weekly. lectures on Mondays Official course page: https://courses.helsinki.fi/fi/tkt21008/ Course structure is in wiki: https://wiki.helsinki.fi/display/cprogramming2015/ Exercise submission on our own server: http://tmc.mooc.fi/hy The course: Programming in C, 2018-2019 Grading based on Examinarium exam only - course is a mix of self-study course and support structures (= lectures & guidance) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 3

Exam Paper-based exam on computer No compiler No man pages No book or other material available Exam will have 4 questions, group names are Command-line arguments Arrays and/or other data types Files Linked lists Exam question randomly selected for each group Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 4

Examinarium exam No fixed schedule (exam time 175 minutes) Register and select your own exam time in https://examinarium.helsinki.fi/enroll/tkt21008/exa m/9909 This course s exam will be open until end of May. You can try only once until your answer is graded Retry possible only once you know the result of previous exam Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 5

Course material Use a course book! ONE good C course book is a MUST: Kernighan & Richie: C programming language Müldner : C for Java programmer King: C Programming, A Modern Approach Tens of other options also exists Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 6

TMC test my code TMC checks automatically the programming tasks and maintains the list of accepted tasks. Online tool, so can be used from home or at university If needed: there will be guidance session (2 hours per week) in computer class room. Possibility to get teacher review (must be submitted for review!) Please use only when needed to keep the review queue manageable Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 7

C language C assumes that programmer is intelligent enough to use all of its constructs wisely, and so few things are forbidden. Closely tight with UNIX same original developers Low-level language explicit memory allocation and deallocation! allows operations on the memory addresses and bit-level allows dynamic type changes of variables important concept: POINTER (= memory address) C can be a very useful and elegant tool. People often dismiss C, claiming that it is responsible for a bad coding style. The bad coding style is not the fault of the language, but is controlled (and so caused) by the programmer. Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 8

Comparison of C and Java from Müldner: C for java programmers uprimitive data types: character, integer, and real. In C, they are of different sizes, there is no Unicode 16-bit character set ustructured data types: arrays, structures and unions. In C, arrays are static there are no classes ucontrol structures are similar ufunctions are similar www.cs.helsinki.fi

Comparison of C and Java ujava references are called pointers in C. ujava constructs missing in C (ANSI): packages threads exception handling garbage collection standard Graphical User Interface (GUI) built-in definition of a string standard support for networking support for program safety. www.cs.helsinki.fi

C key features Low level language: Memory address and value are visible Pointer is a variable that stores an address Old language: No objects No garbage collection Explicit memory management Functions to allocate and free memory areas Dynamic memory allocations in heap Static variables in stack stack heap static global variables code Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 11

Xptr DC 0 X DC 12 LOAD R1, =X ; R1 230 STORE R1, Xptr LOAD R2, X ; R2 12 LOAD R3, @Xptr ; R3 12 Addresses and values Xptr=225: memory 230 12345 TITO Variable X s address is 230 (&X) Variable X s value is 12 (X) Pointer Xptr s address is 225 (&Xptr) X=230: Pointer Xptr s value is 230 (Xptr) Address of some data (now the address of X) The value of the integer (*Xptr) that Xptr points to is 12 In C language as: Y = *Xptr; /* value of the location Xptr points to */ 12556 128765 12222 12 12998 Faculty of Science Department of Computer Science 5.9.2018 12

Modular programming in C C does not support objects or modular programming, but it has features that can be used to mimic them - Functions and function prototypes - Header files Using these features you can separate the interface and implementation *.c hidden implementation *.h public interface Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 13

Standard libraries Each library contains a set of useful functions A header file gives the function signatures and type definitions for that particular library stdio.h math.h assert.h is usually always used, since it contains the functions for reading and writing contains mathematical functions macro assert to help locate mistakes 29 header files in total (see wikipedia for the list) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 14

Example program #include<stdio.h> /*Header file of a library*/ int main(int argc, char **argv) /* The main function */ { int x, *y, z; /*Variable Declaration*/ if ( (y = malloc (sizeof(int)) ==NULL) return(1); x = 5; *y = 10; z=x+*y; printf ("The sum is %d", z); free(y); return (0); /* standard return value for success */ } Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 15

Programming style Write clear and easily understandable code (Java programming course style is good!) Cryptic and concise code has no value itself, the clarity is more important do { if (scanf( %d, &i)!=1 i == SENTINEL) break; if (i>maxi) maxi = i; } while (1); void show (char *p) { char *q; printf( [ ); for (q=p; *q!= \0 ; q++) printf( %c, *q); printf( ]\n ); } www.cs.helsinki.fi

Macro Function calls Function ends #include<stdio.h> #include<string.h> #define SUCCESS 0 #define FAILURE -1 int main(void) { char pass_buff[50] = {0}; printf("\n Enter the password..."); //Get the password from user fgets(pass_buff,sizeof(pass_buff)-1,stdin); //Make sure that the extra(last) character //picked up from stdin is washed off } } //from buffer. pass_buff[strlen(pass_buff)-1] = '\0'; if(! (strcmp(pass_buff,"linux"))) { // Passwords match printf("\n Passwords Match..SUCCESS\n"); return SUCCESS; } else { // Passwords do not macth printf("\n Passwords do not match...failure\n"); return FAILURE; Faculty of Science Department of Computer Science Another example Emply lines would make it more readable Main function From: mylinuxbook.com Array = continuous memory area (here string) 5.9.2018 17

Programming in C Command-line interface needs only shell, no graphical interface the old fashioned way most UNIX experts still do it this way explicit compilation and linking Integrated Development Environments (IDEs) TMC is integrated with NetBeans Eclipse is another very popular one Program still needs to be compiled and linked before execution IDE might hide these phases Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 18

Development process with command-line interface Write program Using suitable editor (vim, nano, emacs,...) Must produce plain text file Compile Link Select the correct compiler and arguments (gcc -c) Link the compiled modules to form a program (gcc) Execute Executing or running the program www.cs.helsinki.fi

Compiling (short program, all in one file) Compile gcc helloworld.c or gcc o helloworld \ helloworld.c Compiler does preprocessing, actual compilation and linking... and produces the executable file a.out or int main (void) { printf( Hello world \n ); return 0; } helloworld www.cs.helsinki.fi

gcc --help Usage: gcc [options] file... Option -- help lists all possible options and features of the compiler, there are plenty -c compile and assemble, but do not link -o <file> place the output into <file> www.cs.helsinki.fi

Compiling: gcc -ansi -pedantic -Wall int main (void) { printf( Hello world \n ); return 0; } Options Wall and pedantic show all possible warnings (used by TMC) Option ansi makes sure that the compiler follows standard (some differences in gcc exist) gcc -ansi -pedantic -Wall -o helloworld helloworld.c /home/fs/niklande/c-luennot/esimerkit/helloworld.c: In function `main': /home/fs/niklande/c-luennot/esimerkit/helloworld.c:3: warning: implicit declaration of function `printf' Faculty of Science Department of Computer Science #include <stdio.h> int main (void) { printf( Hello world \n ); return 0; } www.cs.helsinki.fi 5.9.2018 22

Structuring a small C program: order of elements in the file #include directive to use (standard) libraries and header files Defining constants and types Easy to locate, modify and control Function prototypes (before the function in used) Function main (every program has one) execution starts here and ends when the main returns. Function definitions (=code of the function) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 23

What if you have a larger project? - Split to multiple files and libraries main sub1 sub2 sub3 sub4 subsub1 subsub2 subsub2 Functions of standard libraries Modularity at the function level Programmers own libraries of functions Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.201824

Multiple modules (separate source files with headers) /* main.c */ #include <stdio.h> #include eka.h #include toka.h int main (void) { eka(); toka (); return 0; } /* eka.c */ #include <stdio.h> #include eka.h void eka (void) { puts( eka ); } /* eka.h */ /* toka.c */ #include <stdio.h> #include toka.h void toka (void) { puts( toka ); } /* toka.h */ Could write everytime: void eka (void); gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Faculty of Science Department of Computer Science void toka (void); www.cs.helsinki.fi Instead, use makefile 5.9.2018 25

Program has multiple files and modules Every program file is compiled separately to create object module (or library) gcc c main.c The modules are then linked together to form the complete program gcc o program main.o eka.o toka.o Usually compiled with make (executes a sequence of commands) www.cs.helsinki.fi

makefile gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Create makefile once, use it multiple times make NOTE: tab, not spaces # makefile CC = gcc ansi pedantic Wall ohjelma: main.o eka.o toka.o $(CC) o ohjelma main.o eka.o toka.o eka.o: eka.c eka.h $(CC) c eka.c toka.o: toka.c toka.h $(CC) c toka.c main.o: main.c eka.h toka.h $(CC) c main.c www.cs.helsinki.fi

After compiling and linking? We have executable program, but does it work? Try to execute it and test the program Look for errors, locate mistakes - Extra print statements - Read the code, simulate execution, THINK! - Use debugger Write automated tests, evaluate test coverage ( -> course: Software testing) On this course we are satisfied with smoke testing or sanity check. (Program seems to satisfy the desciption.) www.cs.helsinki.fi

Testing Target: find mistakes Covers wide spectrum of possible input values Can be automated (using scripts or special test tools/packages) Not part of the learning goals of this course On this course (smoke test, sanity check) usually enough to check - Correct and incorrect input values - Boundary values(-1,0,1) www.cs.helsinki.fi

Extra print statements #ifdef EXTRAPRINT printf ( Fname: Variable name %d \n, variable); #endif Target: try to understand the functionality of the code. Placed: around the most probably mistake location Usually more handy than debugger, if you have an idea of the error location in advance. gcc D EXTRAPRINT www.cs.helsinki.fi

More advanced tools : assert and valgrind assert macro (in assert.h) helps to check the values of variables same code can be compiled with and without the assert checks Write the asserts in the source code (*.c file) memcheck from valgrind makes it possible to find incorrect memory usage used in some of the acceptance tests run at the tmc server used at run time, execute program within valgrind Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 31

Debugger gdb (gdb) help List of classes of commands: aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands www.cs.helsinki.fi

core dump Crashed program usually produces a file (code dump) that contains state of the memory and registers at the time of crash. This file can be accessed by debugger to find out values of variable and the location of the instruction that crashed the program. This is not covered on the course, but could be very useful to study at some point. www.cs.helsinki.fi

Week1 exercises cover (lecture Mon 10.9.) Learning points: Naming and visibility aspects Variables and simple types (int, float, char) Arrays (=sequence of values in memory) Some standard functions (and using man pages) Input and output Scanf, printf (getc, ) Formatting Stdin, stdout and stderr Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 34

Other Weeks Week2 (17.9.): Pointers, strings, linked lists Presedence and associativity of operators, dynamic memory allocation, address arithmetics Week3 (24.9.): Files Week4 (1.10.): Arrays, command line arguments Pointer arrays, multi-dimensional arrays, Week5 (8.10.): Macros, function pointer, struct, union Week6 (15.10.): Intrusive linked list, bitwise operations Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 35

If time, solve the following problem Design a program that reads n integer values and then determines and outputs whether the sequence entered is sorted in ascending order, decending order, or is unordered. Here is a sample dialog produce by the running program How many integers do you have? 4 Enter the 1st integer: 10 Enter the 2nd integer: 8 Enter the 3rd integer: 6 Enter the 4th integer: 4 Your sequence is sorted in decending order. From: Uckan, Problem solving with C. McGrawHill, 1999. Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 36