CSE 105 Structured Programming Language Presentation - 2

Slides:



Advertisements
Similar presentations
Chapter 4 Computation Bjarne Stroustrup
Advertisements

Lecture 10 Flow of Control: Loops (Part 2) COMP1681 / SE15 Introduction to Programming.
Recursive Descent Technique CMSC 331. UMBC 2 The Header /* This program matches the following A -> B { '|' B } B -> C { '&' C } C -> D { '^' D } D ->
Modern Programming Languages, 2nd ed.
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
Chapter Three Arithmetic Expressions and Assignment Statements
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 2212a/b - UWO1 Structural Testing Motivation The gcov Tool An example using gcov How does gcov do it gcov subtleties Further structural.
CS110 Programming Language I
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
CS1010 Programming Methodology
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
Engineering Computing I Chapter 1 – Part B A Tutorial Introduction continued.
Character Input and Output C and Data Structures Baojian Hua
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Imperative Programming Prof. Béat Hirsbrunner Amine Tafat, PhD Student Matthias Buchs and Raphaël Lesceux, Graduate Students Department of Informatics.
. Welcome to PLAB. Course Staff Teacher:  Nir Friedman Teaching Assistants:  Yoseph Barash  Liad Blumrosen  Michael Okun.
CS 201 Functions Debzani Deb.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Character Input and Output
Computer Programming and Problem Solving Ke shuwei.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
CS1020E Sitin 1 Discussion -- Counting Palindromes.
Designing with Procedures 1. Designing a Program with Procedures If the code for your program is going to be less than one page, normally don’t bother;
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Flow of Control Part 1: Selection
Advanced Computer Science Lab Coding Style & Documentation.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Software Development Problem Analysis and Specification Design Implementation (Coding) Testing, Execution and Debugging Maintenance.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
Prof. Béat Hirsbrunner Ammar Halabi, PhD student (exercises) Dani Rotzetter, Master student (exercises) Bachelor students : Major in computer science (3rd.
2/22/2016 1R. Smith - University of St Thomas - Minnesota CISC 130: Today’s Class History Paper scheduleHistory Paper schedule RecapRecap Plus PlusPlus.
ATS Programming Short Course I INTRODUCTORY CONCEPTS Tuesday, Feb 10th, 2009 Introduction to Programming.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich.
Basic Data Types & Memory & Representation
Program style.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Week 3 Part 2 Kyle Dewey.
Control Flow (Chapter 3)
Bill Tucker Austin Community College COSC 1315
Decisions Chapter 4.
Chapter 4 (Conditional Statements)
Week 4 - Monday CS222.
Structured Programming (Top Down Step Refinement)
C Programming Variables.
CS1100 Computational Engineering
The Elements of Programming Style
We’re moving on to more recap from other programming languages
Herbert G. Mayer, PSU CS Status 8/2/2013
The Elements of Programming Style
FOR statement a compact notation for a WHILE e.g. sumgrades = 0;
Variables in C Topics Naming Variables Declaring Variables
Creating Maintainable code
CS31 Discussion 1D Fall18: week 2
C Structures and Commands
CSE 206 Course Review.
Class code for pythonroom.com cchsp2cs
C++ Programming Lecture 7 Control Structure I (Selection) – Part II
Creating readable code
Presentation transcript:

CSE 105 Structured Programming Language Presentation - 2 Programming Style CSE 105 Structured Programming Language Presentation - 2 Thanks to Arie Rapoport, cs.huji.ac.il

Word Counting (KnR – 1.5.4) #include <stdio.h> Start Word Counting (KnR – 1.5.4) state=OUT nl=nw=nc=0 #include <stdio.h> #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ /* count lines, words, and characters in input */ main( ) { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; while ((c = getchar()) != EOF) { ++nc; if (c == ‘\n‘) ++nl; if (c == ‘ ‘ || c == ‘\n‘ || c == ‘\t‘) sate = OUT; else if (state == OUT) { state = IN; ++nw; } printf(“%d %d %d\n”, nl, nw, nc); c = getchar() c != EOF N Y ++nc; c==‘\n‘ Y N ++nl c is white- char state== OUT N Y Y state = OUT state=IN ++nw print nl,nw,nc End

Program Style Readability Clarity Common sense Right focus

What’s in a name Example More reasonable #define ONE 1 #define TEN 10 #define TWENTY 20 More reasonable #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20

What’s in a name Use descriptive names for global variables int npending = 0; // current length of input queue Naming conventions vary numPending num_pending NumberOfPendingEvents …

What’s in a name Compare and Use short names for locals for( theElementIndex = 0; theElementIndex < numberOfElements; theElementIndex++ ) elementArray[theElementIndex] = theElementIndex; and for( i = 0; i < nelems; i++ ) elem[i] = i; Use short names for locals

What’s in a name Consider The word “queue” appears in 3 different ways int noOfItemsInQ; int frontOfTheQueue; int queueCapacity; … The word “queue” appears in 3 different ways Be Consistent Follow naming guidelines used by your peers

What’s in a name Use active name for functions Compare now = getDate() Compare if( checkdigit(c) ) … to if( isdigit(c) ) … Accurate active names makes bugs apparent

Indentation Use indentation to show structure Compare to for(n++; n <100; field[n++] = 0); c = 0; return ‘\n’; to for( n++; n <100; n++) field[n] = 0; c = 0; return ‘\n’;

Expressions Use parenthesis to resolve ambiguity Compare to leap_year = y % 4 == 0 && y %100 != 0 || y % 400 == 0; to leap_year = ((y % 4 == 0) && (y %100 != 0)) || (y % 400 == 0);

Statements Use braces to resolve ambiguity Compare to if( i < 100 ) x = i; i++; to { }

Idioms Do not try to make code “interesting” while( i <= n – 1 ) array[i++] = 1; … for( i = 0; i < n; ) for( i = n; --i >= 0; ) array[i] = 1; for( i = 0; i < n; i++ ) Explain idioms as patterns for writing code in the programming language, a.k.a. conventions This is the common “idiom” that any programmer will recognize

Idioms Use “else if” for multi-way decisions if ( cond1 ) statement1 else if ( cond2 ) statement2 … else if ( condn ) statementn else default-statement

Idioms if( x > 0 ) if( y > 0 ) if( x <= 0 ) if( x+y < 100 ) { ... } else printf(“Too large!\n" ); else printf("y too small!\n"); printf("x too small!\n"); if( x <= 0 ) printf("x too small!\n"); else if( y <= 0 ) printf("y too small!\n"); else if( x+y >= 100 ) printf("Sum too large!\n" ); else { ... }

Comments Don’t belabor the obvious // return SUCCESS return SUCCESS; // Initialize “total” to “number_received” total = number_received; Test: does comment add something that is not evident from the code The best documentation is a good code styling

Comments Document each function // random: return a random integer in [0..r] int random( int r ) { return (int)floor(rand()*r); }

Comments A more elaborate function comment // // GammaGreaterThanOne( Alpha ) // Generate a gamma random variable when alpha > 1. // Assumption: Alpha > 1 // Reference: Ripley, Stochastic Simulation, p.90 // Chang and Feast, Appl.Stat. (28) p.290 double GammaGreaterThanOne( double Alpha ) { … }

Comments Don’t comment bad code – rewrite it! Instead … // If result = 0 a match was found so return // true; otherwise return false; return !result; Instead return matchfound;

Style recap Descriptive names Clarity in expressions Straightforward flow Readability of code & comments Consistent conventions & idioms

Why Bother? Good style: Sloppy code bad code Easy to understand code Smaller & polished Makes errors apparent Yields a good grade Sloppy code bad code Hard to read Broken flow Harder to find errors & correct them, maintenance.