welcome to plab. course staff teacher: nir friedman teaching assistants: yoseph barash liad...
Post on 21-Dec-2015
222 Views
Preview:
TRANSCRIPT
Communications
WWW:http://www.cs.huji.ac.il/~plab
Email: Personal questions should be sent only to plab@cs
Newsgroups: local.course.plab.stud local.course.plab.ta (moderated)
Course Objectives
Procedural programming language (C). Pointers (C/C++) Generic programming (C++ templates) Design patterns (STL, streams, and more) Practice of programming:
Style Testing & Debugging Efficiency & Portability Modularity
Books “The C Programming Language” , 2nd Edition,
Brian W. Kernighan & Dennis M.Ritchie “C++ Programming Language”, 3rd Edition,
Bjarne Strousrtup “The C++ Primer”, Stanley Lippman “C++ for Java Programmers”, Timothy Budd “C++ How to Program”, Harvey Deitel & Paul Deitel “The Practice of Programming”, Brian W. Kernighan
& Rob Pike “Programming Pearls” 2nd Edition, Jon Bentley
Course Grading
6-7 programming exercises Mid-term exam Final exam Final grade 60% exercises and 40% exam.
Shortage in computers - don’t wait for the last minute.
History
C C++ JAVA
70’s – Development of UNIX. (Richie+Kernigham – Bell labs)
80’s – Large efficient code. (Stroustrup – Bell labs)
90’s – Language for the web. (Sun Microsystems)
Simple to convert to machine code.
Advanced Programming
Fast and Efficient Secure and Safe
Welcome to Plab Easy to avoid bugsEasy to Debug
C – Design Decisions
“Bare bones” – the language leaves maximal flexibility with the programmer Efficient code (operating systems) Full control on memory & CPU usage
High-level Type checking High-level constructs
Portable Standard language definition Standard library
C – Warning Signs
No run-time checks Array boundary overruns Illegal pointers
No memory management Programmer has to manage memory
C++ - OO extension of C
Classes & methods OO design of classes
Generic programming Template allow for code reuse
Stricter type system Some run-time checks & memory control
First Program in C
// This is a comment
// This line defines standard I/O library
#include <stdio.h>
// main – name of the main part of the program
int
main()
{ // {…} define a block
printf("Hello class!\n");
return 0;
}
Second Program#include <stdio.h>
int
main()
{
int i; // declares i as an integer
int j = 0; // declares j as an integer, and initializes it to 0
// for( initial ; test condition ; update step )
for( i = 0; i < 10; i++ )
{
j += i; // shorthand for j = j + i
printf("%d %d %d\n", i, j, (i*(i+1))/2); }
return 0;
}
Running…
> g++ -o loop loop.c
> loop
0 0 0
1 1 1
2 3 3
3 6 6
4 10 10
5 15 15
6 21 21
7 28 28
8 36 36
9 45 45
Character Input/Output
#include <stdio.h>
int
main()
{
char c;
while( (c = getchar()) != EOF )
putchar(c);
return 0
}
Print header#include <stdio.h>
#define HEADER 10
int main()
{
int n = 0;
char c;
while( ((c = getchar()) != EOF) && (n < HEADER) )
{
putchar(c);
if( c == '\n' )
n++;
}
return 0;
}
Functions
C allows to define functions
Syntax:int
power( int a, int b )
{
…
return 7;
}
Return type Parameter declaration
Return statement
Procedures
Functions that return void
void
proc( int a, int b )
{
…
return;
}
Return w/o value(optional)
Example – printing powers#include <stdio.h>
int
power( int base, int n )
{
int i, p;
p = 1;
for( i = 0; i < n; i++ )
p = p * base;
return p;
}
int
main()
{
int i;
for( i = 0; i < 10; i++ )
printf("%d %d %d\n",
i,
power(2,i),
power(-3,i) );
return 0;
}
Functions Declaration“Rule 1”: A function “knows” only functions which were defined above it.
void funcA(){ ...}
void funcB(){ funcA();}
void funcC(){ funcB(); funcA(); funcB();}
void funcA(){ ...}
void funcB(){ funcC();}
void funcC(){ funcA();}
Error: funcC is not known yet.
Amendment to “Rule 1” : Use forward declarations.void funcC(int param); // or void funcC(int);
void funcA();{ ...}
void funcB(){ …. funcC(7);}
void funcC(int param){ ….}
Functions Declaration
Powers revisted#include <stdio.h>
// Forward decleration
int power( int m, int n);
int main()
{
int i;
for( i = 0; i < 10;i++ )
printf("%d %d %d\n",
i, power(2,i),
power(-3,i) );
return 0;
}
int
power( int base, int n )
{
int i, p;
p = 1;
while( n > 0 )
{
if( n % 2 )
p *= base;
base *= base;
n /= 2;
}
return p;
}
What’s in a name
Example#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
Comparefor( theElementIndex = 0;
theElementIndex < numberOfElements;
theElementIndex++ )
elementArray[theElementIndex] = theElementIndex;
andfor( i = 0; i < nelems; i++ )
elem[i] = i;
Use short names for locals
What’s in a name
Considerint 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
now = getDate()
Compare if( checkdigit(c) ) …
to if( isdigit(c) ) …
Accurate active names makes bugs apparent
Indentation
Use indentation to show structure
Compare 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 parens to resolve ambiguity
Compareleap_year = y % 4 == 0 && y %100 != 0
|| y % 400 == 0;
toleap_year = ((y % 4 == 0) && (y %100 != 0))
|| (y % 400 == 0);
Statements
Use braces to resolve ambiguity
Compareif( i < 100 )
x = i;
i++;
toif( i < 100 )
{
x = i;
}
i++;
Idioms
Do not try to make code “interesting”
i = 0;
while( i <= n – 1 )
array[i++] = 1;
…
for( i = 0; i < n; )
array[i++] = 1;
…
for( i = n; --i >= 0; )
array[i] = 1;
…
for( i = 0; i < n; i++ )
array[i] = 1;
This is the common “idiom” that any programmer will recognize
Idioms
Use “else if” for multiway decisions
if ( cond1 )
statement1
else if ( cond2 )
statement2
…
else if ( condn )
statementn
else
default-statement
Idiomsif( x > 0 )
if( y > 0 )
if( x+y < 100 )
{
...
} else
printf(“Too large!\n" );
else
printf("y too small!\n");
else
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
Comments
Introduce each function
// random: return a random integer in [0..r]
int random( int r )
{
return (int)floor(rand()*r);
}
CommentsA 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!
…
// 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
top related