Programming in C week 1 meeting Tiina Niklander

Similar documents
Programming in C First meeting

Programming in C First meeting Tiina Niklander

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

PRINCIPLES OF OPERATING SYSTEMS

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

CS 253: Intro to Systems Programming 1/21

CS240: Programming in C

CSE 351. Introduction & Course Tools

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Short Notes of CS201

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

Reviewing gcc, make, gdb, and Linux Editors 1

Lecture 07 Debugging Programs with GDB

CS201 - Introduction to Programming Glossary By

The C standard library

Problem Set 1: Unix Commands 1

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

Programming in C UVic SEng 265

CS Basics 15) Compiling a C prog.

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

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

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

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

CSCI 2132 Final Exam Solutions

Recitation: Cache Lab & C

Exercise 1: Basic Tools

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

CSE 303, Winter 2006, Final Examination 16 March Please do not turn the page until everyone is ready.

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

CSCI 171 Chapter Outlines

Laboratory 1 Semester 1 11/12

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

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

2 Compiling a C program

Programming in C in a UNIX environment

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

Introduction to C. CS2023 Winter 2004

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

C & Data Structures syllabus

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

Lecture 03 Bits, Bytes and Data Types

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

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

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

Programming in C Lecture Tiina Niklander

Intermediate Programming, Spring 2017*

C / C++ Coding Rules

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

C introduction: part 1

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Lectures 5-6: Introduction to C

Course Information and Introduction

Intermediate Programming, Spring 2017*

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

CSE 333 Midterm Exam 7/29/13

Tutorial 1 C Tutorial: Pointers, Strings, Exec

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

Formal Methods for C

Introduction to Supercomputing

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Recitation 2/18/2012

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

COSC Software Engineering. Lecture 16: Managing Memory Managers

CSE 374 Programming Concepts & Tools

CS240: Programming in C. Lecture 2: Overview

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

Lectures 5-6: Introduction to C

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

Student Number: Computer Science 211b Final Examination. 28 April hours

ECE 250 / CS 250 Computer Architecture. C Programming

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

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

just a ((somewhat) safer) dialect.

In the case of the dynamic array, the space must be deallocated when the program is finished with it. free(x);

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

Understanding Pointers

BİL200 TUTORIAL-EXERCISES Objective:

High Performance Computing MPI and C-Language Seminars 2009

ECE 250 / CPS 250 Computer Architecture. C Programming

Exercise Session 6 Computer Architecture and Systems Programming

C programming basics T3-1 -

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

Reliable C++ development - session 1: From C to C++ (and some C++ features)

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

Transcription:

Programming in C week 1 meeting 2.9.2015 Tiina Niklander Faculty of Science Department of Computer Science 3.9.2015 1

Course structure Based on C programming course in Aalto, but with some exercises created locally Course structure is in wiki: https://wiki.helsinki.fi/display/cprogramming2015/ Exercise submission on our own server: http://tmc.mooc.fi/hy use your student ID as your username! Grading based on TMC exercises + Exam!!! Faculty of Science Department of Computer Science 3.9.2015 2

Course material Use a course book and some extra on-line material, e.g. Aalto on-line material: http://src.aalto.fi/c 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 Faculty of Science Department of Computer Science 3.9.2015 3

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, pure ANSI C only Faculty of Science Department of Computer Science 3.9.2015 4

TMC Deadline Tuesdays at 19.00 TMC checks automatically the programming tasks and maintains the list of accepted tasks. On-line tool, so can be used from home or at university Paja times (in B221): - Thu 3.9. at 12.15-14 is only paja this week. - Usually on Mon 13-18 & Tue 13-18 Faculty of Science Department of Computer Science 3.9.2015 5

Exam Programming on paper!!! Last Fall s exam had 4 questions Calculate averages (function + main + command line parameters/arguments) Personal contacts (create data structure + handling functions write comments, but not all codes) File handling and I/O streams essay Errors and mistakes evaluate an existing program 2,5 hours Faculty of Science Department of Computer Science 3.9.2015 6

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 3.9.2015 7

Xptr DC 0 X DC 12 LOAD R1, =X STORE R1, Xptr LOAD R2, X LOAD R3, @Xptr ; R1 230 ; R2 12 ; 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 3.9.2015 8

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 3.9.2015 9

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; } 3.9.2015 10

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); Instead, use makefile 3.9.2015 11

makefile gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Write makefile just once Use several times with command make make Faculty of Science Department of Computer Science # 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 3.9.2015 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 hidden implementation public interface Faculty of Science Department of Computer Science 3.9.2015 13

Structuring a small C program: order of elements in the file #include directive to use (standard) libraries Defining constants ad types Easy to locate, modify and control Function prototypes (before the functions in used) Function main (every program has one) Function definitions (=code of the function) Faculty of Science Department of Computer Science 3.9.2015 14

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 3.9.201515

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 3.9.2015 16

Comparison of C and Java from Mülder: 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

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.

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 ); }

What do the following sentences do? while (*q++ = *p++); if ((c=fgetc(filehandle)) == EOF) for (i=a, j=b; i<=j; i += 2, j += 2)

#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 From: mylinuxbook.com 3.9.2015 21

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 3.9.2015 22

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

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>

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

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)

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

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.)

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)

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.

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

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.