Programming Style Guide v1.1

Similar documents
Introduction to C Programming

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Programming for Engineers Introduction to C

Fundamental of Programming (C)

2. Numbers In, Numbers Out

CpSc 1111 Lab 5 Formatting and Flow Control

2. Numbers In, Numbers Out

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Full file at

CpSc 1111 Lab 4 Formatting and Flow Control

C: How to Program. Week /Mar/05

Fundamentals of Programming

printf( Please enter another number: ); scanf( %d, &num2);

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

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CSE 142/143 Unofficial Style Guide

C Formatting Guidelines

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CS 251 Intermediate Programming Coding Standards

Differentiate Between Keywords and Identifiers

Use of scanf. scanf("%d", &number);

Chapter 4 C Program Control

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

Chapter 2 - Introduction to C Programming

Chapter 2 Basic Elements of C++

Visual C# Instructor s Manual Table of Contents

Documentation Requirements Computer Science 2334 Spring 2016

Lecture 6. Statements

CSE 5A Introduction to Programming I (C) Homework 4

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

BLM2031 Structured Programming. Zeyneb KURT

VARIABLES & ASSIGNMENTS

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Fundamentals of Programming Session 4

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

Programming and Data Structures

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

Coding Standards for C

CS242 COMPUTER PROGRAMMING

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

Coding Standards for C

CMSC 201 Fall 2018 Python Coding Standards

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

6.096 Introduction to C++ January (IAP) 2009

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C Programming

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

The C++ Language. Arizona State University 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Basics of Programming

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

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

Chapter 3: Arrays and More C Functionality

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

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

Key Differences Between Python and Java

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

LECTURE 02 INTRODUCTION TO C++

2.8. Decision Making: Equality and Relational Operators

C++ Programming: From Problem Analysis to Program Design, Third Edition

Fundamentals of Programming Session 8

Objectives. In this chapter, you will:

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

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

Coding Standard for ECE3090 August 24, 2005

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

Coding Standards for Java

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

ARG! Language Reference Manual

C++ Programming Style Guide

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Introduction to Computer Science Midterm 3 Fall, Points

Java Programming Style Guide

Chapter 6. Decision and Control Statements

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

INTRODUCTION 1 AND REVIEW

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Introduction. Pretest and Posttest Loops. Basic Loop Structures ว ทยาการคอมพ วเตอร เบ องต น Fundamentals of Computer Science

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

UNIT- 3 Introduction to C++

Full file at

Chapter 4 C Program Control

CS 351 Design of Large Programs Coding Standards

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

Chapter 2 Author Notes

Computer Programming : C++

Operators and Control Flow. CS449 Fall 2017

Transcription:

Oregon State University Intro to programming Source Code Style Guide Modified from: OREGON INSTITUTE OF TECHNOLOGY COMPUTER SYSTEMS ENGINEERING TECHNOLOGY Modified by: Joseph Jess Programming Style Guide v1.1 For CS 161, 162, 165, and possibly other classes, as requested Examples in this are currently given in C, but other examples will become available as needed for courses or upon request. Page 1 of 13

Table of Contents 1 Documentation...3 1.1 Main Documentation Header Block...3 2 Naming Conventions...5 2.1 Variables...5 2.2 Constants...6 2.3 Functions, Methods, Subroutines, whatever your languages calls these...6 2.3.1 Function Names...6 2.3.2 Function Declarations...7 2.3.3 Function Definitions...8 3 Indentation...9 4 Parentheses and Precedence Order...9 5 White Space...10 6 Example Program...11 Page 2 of 13

Programming Style Guide The purpose of this document is to set forth guidelines for the formatting of programs. The goal is to create programs that are easier to read, understand, and maintain. 1 Documentation Take credit for your work. Every program that you write should have a leading comment block that identifies the author and the purpose of the program. 1.1 Main Documentation Header Block This header block will be the first part of your source file. The header block will consist of the following sections: Author: Date Created: Last Modification Date: File name: Your name Starting date of the project Last time the project was changed The name of the source code file (useful if printed) Overview: This section specifically states what the program does. Input: This section will state where the input for the project is coming from, what the input represents, and any limitations placed on the input. If the input is coming from a file, the filename, type of file (such as text or binary), and a sample format of the file will also be given. Output: This section states what your program produces as output, form of the output, examples, and where the output is going. Page 3 of 13

/ Author: Todd Breedlove Date Created: 12/17/96 Last Modification Date: 1/5/01 Filename: Lab1.c Overview: This program will read in a name and four grades and calculate the average. The average will then be used to find the number of each letter grade (i.e. 5 A's, 6 B's, etc.). The program will also find the highest average and the lowest average in the class. Input: The input will consist of a name and four scores for a varying number of people and is read from the file c:\cst116\lab1.dat. The data file is a text file in the expected format of: first_name last_name score1 score2 score3 score4 Example input file contents: Todd Breedlove 90 90 90 90 Bill Jones 85 65 65 65 Output: The output of this program will be the cumulative number of each letter grade. The program will also display the name of the person with the lowest and the highest average for the class and their averages. The output will be to the screen and will have the form: Number of A's: 10 Number of B's: 5 Number of C's: 10 Number of D's: 5 Number of F's: 10 Todd Breedlove has the highest average of: 90 Bill Jones has the lowest average of: 75 / Page 4 of 13

2 Naming Conventions Describe what a variable or function means or does, rather than how it works!! Keep in mind that many languages are case sensitive (including C)! 2.1 Variables Variable names must be descriptive of their purpose. All variable names must start in lowercase. Multiple words will be either camel case with upper character for the next word or all lower case separated by an underscore. Either way is acceptable but the naming convention must be consistent throughout the program. All variable declarations should have a comment explaining the purpose of the variable. Some example variable declarations and comments are provided below. int filesize = 25; // size of the input file char selection; // users selection of menu item const int MAX_SIZE = 50; // constant maximum size of file_name char file_name[max_size]; // the file name of the output file int i = 0, j = 0; // index variables for loops Defining variables with names like x, y, or z, gives no insight into how the variable is to be used or the types of values that can be assigned, unless taken from a well-known mathematical equation, which you should reference explicitly. Although it may take a little longer to type out a descriptive variable name, doing so can save hours of frustration when trying to correct a program that doesn't work or when trying to modify a program that you haven t worked on for awhile. One common exception to the descriptive naming rule is that variables used solely for iteration purposes (such as an index in a for loop), may be named with single letters. Preferred letters for this purpose are i, j, and k. A comment should exist where these variables are declared that explains that they are for use as index variables. Such variables should never be used for any other purpose. Page 5 of 13

2.2 Constants Constants should be given names in ALL_CAPITAL_LETTERS and USE_UNDERSCORES to separate words. Constants that apply only to a specific translation unit should be defined as a static constant within the file, to ensure that programmers wishing to reuse your class do not overlook them. const int MAX_SIZE = 15; static const int MAX_LENGTH = 63; 2.3 Functions, Methods, Subroutines, whatever your languages calls these... 2.3.1 Function Names Function names must be descriptive of their purpose. Since functions are orders to do something, function names should start with strong verbs. Function names should start with uppercase letters and have uppercase letters at word boundaries. This distinguishes your functions from standard library functions and also prevents variable name and function name conflicts. SelectionSort(); GetMenuSelection(); Functions should be written to do one purpose and should not be longer than one page, including appropriate documentation. Exceptions will be made to this rule if deemed necessary or appropriate. Check with instructor. When printing source code, more than one function may be on any given page as long as there are no functions that are broken by a page break. Page 6 of 13

2.3.2 Function Declarations Comments need to be clear, concise and should specifically describe what the function does, not how it works. There are two types of declaration comments: 1) If the declaration appears in the.c file, then you are required to use a one or two-line comment above the function declaration to explain the purpose of the function. // This function will read the input data for each plant void ReadInputData( int plant_array[], int array_size); 2) If the declaration appears in a separate.h file, then you are required to use a full comment block listing each function, its purpose, entry conditions, and exit conditions. Examples: / void ReadInputData(int plant_array[], int array_size); Purpose: This function reads the input data for each plant. Entry: array_size is the declared size of the array plant_array. Exit: For plant_number = 1 through array_size: plant_array[plant_number - 1] equals the total production for plant number plant_number. int GetTotal(void); Purpose: This function reads non-negative integers from the keyboard and accumulates the total production per plant. Entry: none. Exit: Accumulate the total units produced by each department of a plant and end input with a sentinel input number ( -1 ). void clear_buffer(void); Purpose: Cleaning the input buffer of left over data. Entry: none. Exit: (hopefully) leaves the standard input buffer empty. / void ReadInputData( int plant_array[], int array_size); int GetTotal(void); void clear_buffer(void); Page 7 of 13

2.3.3 Function Definitions Each function definition should have a comment block above the function that describes the entry and exit conditions that apply to the function. If no entry condition exists, then state none. The exit condition should explain what the function does, what it returns (if it is a non-void function), and which, if any parameters are modified. / Entry: array_size is the declared size of the array plant_array. Exit: For plant_number = 1 through array_size: plant_array[plant_number - 1] equals the total production for plant number plant_number. Purpose: Read the input data for each plant / void ReadInputData(int plant_array[], int array_size) int plant_number; for (plant_number = 0; plant_number < array_size; plant_number++) printf("\nenter production data for plant number %d\n", plant_number + 1); plant_array[plant_number] = GetTotal(); Page 8 of 13

3 Indentation To improve the readability of programs, and to aid you in correcting your programs, there should be indentation or tab that indicates different blocks of statements. An example of a properly indented program is provided below. void main() int num; printf("please enter a number: "); scanf("%d", &num); if (num == 0) printf("zero\n"); else printf("the number is greater than 0, or "); printf("the number is less than 0"); printf("\ndone"); The curly braces should be placed immediately beneath the line, lined up at the same indentation level. It is easy to see that every opening brace has a closing brace at the same level of indentation. This makes it easier to determine which block a brace is closing. Also, it is MUCH easier to verify that every closing brace has a matching opening brace. You may think you have started a block but may have inadvertently left off the opening brace at the end of a statement. 4 Parentheses and Precedence The operator precedence order is a rather tricky thing. Rather than relying on rules of precedence, mathematical and relational expressions should make use of some parentheses to clarify how the expression is to be evaluated (to be clear to programmers what your intended order was). x = (3 x + y) / z + (3 a) / b; Although the program will compile and run properly, you or someone required to maintain your program may forget the order of evaluation, or simply make a mistake, and cause the program to stop functioning properly. The following statement is a little less easy to understand: x = 3 x + y / z + 3 a / b; Page 9 of 13

5 White Space Add white space (i.e., blank lines and or spaces) to improve readability. In general: Use one blank line to separate logical chunks of code. Avoid using more than one blank line, but DO NOT double space lines of code! Put a blank line before and after each control structure. Place a space after each comma (,) to make programs more readable. (such as variable lists, argument lists, initializer lists, and comments) Place a space on either side of a binary operator. This makes the operator stand out and the program easier to read (but avoid spaces by unary operators such as!,, &, and possibly others). Declare each variable on a separate line. This format allows for placing a descriptive comment next to each declaration. Unless the variables are homogeneous (same data type) and related to the same calculations, then you can place them on the same line. double testaverage(90.0); int firstnumber(3), secondnumber(5); float quizavg, labavg; // Average score for tests // User enters two numbers // Decimal point averages Page 10 of 13

6 Example Program / Author: Naomi West Modified by: Joseph Jess Date Created: 1/24/03 Last Modification Date: 3/05/13 Lab Number: CS161 Lab 1 Filename: Lab1.c Overview: This is a menu driven lab that prompts and gets the user input of four plants For each plant in the array, the program prompts and gets the number of units from each department per plant. Input: There are four manufacturing plants. The user input is a list of numbers entered by the user giving the production for each department in that plant. The list is terminated with a negative number that serves as a sentinel value. Output: The number of the manufacturing plant, the total number of units produced within each plant. The output to the screen will be in the form of: Enter the production data for plant number 1 Enter the number of units produced by each department. Append a negative number to the end of the list. 1 2 3-1 Total = 6 / #include <stdio.h> static const int NUMBER_OF_PLANTS = 4; // This function reads the input data for each plant. void ReadInputData(int plant_array[], int array_size); // This function reads non-negative integers from the // keyboard and accumulates the total sum per plant. int GetTotal(void); //clears the input buffer as best as I know how void clear_buffer(void); int main() // Array of total production for each of the four plants int production[number_of_plants]; char run_again; // user input answer Page 11 of 13

do // Menu to input another plant or exit int i; // loop driver ReadInputData(production, NUMBER_OF_PLANTS); // Input plant data information printf("\ntotal production for each of 4 plant\n"); // Display production // Loop through all the plants for( i = 0; i < NUMBER_OF_PLANTS; i++ ) printf("plant production for plant %d: %d\n", (i + 1), production[i]); printf("test Again? ( Type y or n and return key ): "); scanf("%c", &run_again); // Continue or exit clear_buffer(); while( ( run_again!= 'N' ) && ( run_again!= 'n') ); printf("\n\nnow exiting."); return 0; / Entry: array_size is the declared size of the array plant_array. Exit: For plant_number = 1 through array_size: plant_array[plant_number - 1] equals the total production for plant number plant_number. Purpose: Read the input data for each plant / void ReadInputData(int plant_array[], int array_size) int plant_number; for (plant_number = 0; plant_number < array_size; plant_number++) printf("\nenter production data for plant number %d\n", plant_number + 1); plant_array[plant_number] = GetTotal(); / Entry: none. Exit: Accumulate the total units produced by each department of a plant and end input with a sentinal number (-1). Purpose: Reads non-negative integers from the keyboard and places their total in sum per plant. Page 12 of 13

/ int GetTotal() int total = 0; // total units per plant int next; // unit of a plant department (added to total each iteration) int count = 1; //number of departments // prompt for and get user input printf("enter the number of units per dept.\nenter a negative number to the end the list.\n"); printf("\n\tenter the units produced by department #%d: ", count); scanf("%d", &next); clear_buffer(); // accumulate units per plant while(next >= 0) total += next; ++count; printf("\n enter the units produced by department #%d: ", count); scanf("%d", &next); clear_buffer(); // output total to display printf("total = %d\n", total); return total; / Entry: none. Exit: (hopefully) leaves the standard input buffer empty. Purpose: Cleaning the input buffer of left over data. / void clear_buffer() char ch; //for clearing input buffer //clear buffer for any later input while((ch = getchar())!= '\n' && ch!= EOF) Page 13 of 13