Docsity

Programming Style and Indentation: A Guide for C Programmers, Assignments of Computer Science

Partial preview of the text

Download Programming Style and Indentation: A Guide for C Programmers and more Assignments Computer Science in PDF only on Docsity!

Programming Style

•^

Indentation is required^ – choose one of three forms, depending on

positions of curly braces

•^

Function prototypes are recommended, butnot required

•^

Comments are required in your programs^ – (but not always shown on these slides to save

space)

– more extensive program headers will be required

for homework from now on

Indentation Style 1

int main(){

int index;

/* loop variable */

double sumsquares = 0;

/* result of summing the squares */

/* loop over each number, adding its square to the sum */for ( index = 1; index <= 10; index++ ){

/* compute the square of the index and add to the sum

sumsquares = sumsquares + index * index; } printf("The sum of the squares from 1 to 10 is %4.2lf.\n", sumsquares);

return(0);

Indentation Style 3

int main() {

int index;

/* loop variable */

double sumsquares = 0;

/* result of summing the squares */

/* loop over each number, adding its square to the sum */for ( index = 1; index <= 10; index++ ) {

/* compute the square of the index and add to the sum

sumsquares = sumsquares + index * index; } printf("The sum of the squares from 1 to 10 is %4.2lf.\n", sumsquares);

return(0);

Summary

•^

Indentation of statements for each programblock is required^ – i.e. all statements within curly braces must indent– and bodies with only one statement and no braces

•^

Curly braces may be in one of three styles^ – Lined up vertically directly under the previous line– Lined up vertically indented to the new block– Left curly brace is at end of previous line, while

right curly brace ends the block at the outer level

Function without Prototypes go first

/* function definition */double factorial(int x){

int i; double result = 1.0;for( i = 1; i <= x; i++) { result = result * i; } // to fit function on page!return(result); } int main(void){

int number; double numberfact;printf("What factorial would you like to compute? ");scanf("%i", &number);numberfact = factorial(number);

// function call

printf("Factorial of %i is %lf\n", number, numberfact);return(0); }