Programming in C Variables, Controls, Functions

advertisement
Programming in C
Variables, Controls, Functions
Different Kinds of Languages

Java is an object-oriented programming (OOP) language
 Problem solving centers on defining classes that model “things” like
Trucks, Persons, Marbles, Strings, and CandyMachine
 Classes encapsulate data (instance variables) and code (methods)
C is a procedural language
 Problem solving centers on defining functions that perform a single
service like getValidInt( ), search( ) and inputPersonData( ).
 Data is global or passed to functions as parameters
 No classes
7/28/09
Libraries
• Because Java is an OOP language, its libraries consist of
predefined classes that you can use in your applications
– ArrayList, Scanner, Color, Integer
• Because C is a procedural language, its library consists of
predefined functions.
– Char/string functions (strcpy, strcmp)
– Math functions (floor, ceil, sin)
– Input/Output functions (printf, scanf)
• On-line C/Unix manual -- the “man” command
– Description of many C library functions and Unix commands
– Usage: man <function name> for C library functions
or man <command name> for Unix commands
• man printf
• man dir
– Search for applicable man pages using the “apropos”
command or “man -k”
– Learn to use the man command using “man man”
7/28/09
Hello World
In JAVA -- Hello.java is in a class
package hello;
public class Hello
{
public static void main( String[ ] args )
{
System.out.println( “Hello World” );
}
}
In C -- Hello.c stands alone
#include <stdio.h>
int main( )
{
printf( “Hello World\n” );
return 0;
}
7/28/09
Compiling and Running
a Java Program
unix> javac -d . *.java
Java
Code
Java
Bytecode
Java interpreter
translates bytecode to
machine code in JRE
javac Hello.java
Java compiler
Hello.java
JRE for
Linux
Hello.class
JRE for
Windows
unix> java hello.Hello
7/28/09
Compiling and Running
a C Program
unix> gcc -o hello hello.c
printf.o
hello.c
Source
program
(text)
Prehello.i
processor
(cpp)
Modified
source
program
(text)
unix> hello
7/28/09
Compiler hello.s Assembler hello.o
(cc1)
(as)
Assembly
program
(text)
Relocatable
object
programs
(binary)
Linker
(ld)
hello
Executable
object
program
(binary)
Language Commonality
• C and Java syntax have much in common
–
–
–
–
–
7/28/09
Some Data Types
Arithmetic operators
Logical Operators
Control structures
Other Operators
Data Types
• Both languages support the integral types int, short,
long.
• Both languages support the floating point types double
and float
• Both languages support the character data type char
• Both languages support enumerations - enum
• C allows the signed (default) and unsigned qualifiers
for integral types (char, int, short, long)
• C does NOT support byte (use char instead)
• Both languages support arrays using [ ] and indexing
starting with zero (0).
1/13/10
True and False
• Java supports the bool data type and the keywords true and
false
bool isRed = true;
bool isLarge = false;
• C does not support the bool data type. Integer variables and
expressions are used as instead
– Any non-zero value is considered “true”
– A zero integer value is considered “false”
int isRed = 55;
int isLarge = 0;
1/13/10
/* “true” */
/* “false” */
Arithmetic Operators
Arithmetic operators are the same
= is used for assignment
+, -, (plus, minus)
*, /, % (times, divide, mod)
++, -- (increment, decrement (pre and post))
Combinations are the same
+=, -=, (plus equal, minus equal)
*=, /=, %= (times equal, divide equal, mod equal)
 Arithmetic Practice
 Assignment Practice
7/28/09
Logical Operators
Logical operators are the same in C and Java and
result in a Boolean value.





&& (and)
|| (or)
==, != (equal and not equal)
<, <= (less than, less than or equal)
>, >= (greater than, greater than or equal)
 Boolean Logic Practice
7/28/09
Control Structures
Both languages support these control structures
which function the same way in C and Java
 for loops
 But NOT -- for (int i = 0; i < size; i++)
 while loops
 do-while loops
 switch statements
 if and if-else statements
 braces ( {, } ) are used to begin and end blocks
 Loop Practice
7/28/09
Other Operators
These other operators are the same in C and Java
 ?: (tri-nary “hook colon”)
int larger = (x : y ? x : y);




<<, >>, &, |, ^ (bit operators*)
<<=, >>=, &=, |=,^=
[ ] (brackets for arrays)
( ) parenthesis for functions and type casting
*much more on these later
7/28/09
#defines
• The #define directive can be used to give names to
important constants in your code. This makes your code
more readable and more easily changeable.
• The compiler replaces every instance of the #define name
with the text that it represents.
• Note that there is no terminating semi-colon
#define MIN_AGE 21
...
if (myAge > MIN_AGE)
...
#define HELP “There is no hope”
...
printf( “%s\n”, HELP);
...
1/13/10
typedefs
• C allows you to define new names for existing
data types (NOT new data types)
• This feature can be used to give applicationspecific names to simple types
typedef int Temperature;
typedef long Width;
• Or to give simple names to complex types
- more on this later
• Using typedefs makes future changes easier
and makes the code more relevant to the
application
1/13/10
Enumeration Constants
• C provides the enum as a list of named constant
integer values (starting a 0 by default)
• Names in enums must be distinct
• Often a better alternative to #defines
• Example
enum boolean { FALSE, TRUE };
enum months { JAN = 1, FEB, MAR, APR, MAY,
JUN, JUL, AUG, SEP, OCT, NOV, DEC };
7/28/09
Miscellaneous
• Comments
– Both languages support block comments surrounded by
/* and */
– C DOES NOT support // comment style*
• Declaring variables
– All variables must be declared at the beginning of the
“block” in which they are used
• Typecasting
– Both languages allow typecasting - temporarily treating
a variable as a different type
• temp = (double) degrees / 4;
• Ask me about C99
1/13/10
Functions vs. Methods
•
Java classes include methods which can be called from any code
with appropriate access (recall public methods)
•
C functions are like Java methods, but they don’t belong to any
class. Functions are defined in a file and may be either global to
your program or local to the file in which they are defined*.
Like Java methods, C functions
– Have a name
– Have a return type
– May have parameters
– Pass arguments “by value”
Unlike Java methods, a function in C is uniquely identified by its
name. Therefore, there is no concept of method overloading in C
as there is in Java. There can be only one main( ) function in a C
application.
•
•
*more on this later
7/28/09
C Function Examples
/* returns the average of two integer parameters */
int intAverage( int a, int b )
{
return ( (a + b) / 2 );
}
/* Simulates dog barking */
void bark (int nrTimes)
{
int n;
for (n = 0; n < nrTimes; n++)
printf(“Arf!\n”);
}
7/28/09
Function Prototypes
• A function prototype defines the function’s name,
(note the semi-colon).
return type, and parameters.
• For example from the previous slide
void bark( int n );
int average( int a, int b );
• Before a function may be called, you must provide
its prototype (or the function definition itself) so
that the C compiler can verify the function is being
called correctly.
7/28/09
Recursion
• C functions may be called recursively.
– Typically a function calls itself
• A properly written recursive function has the
following properties
– A “base case” - a condition which does NOT make a
recursive call because a simple solution exists
– A recursive call with a condition (usually a parameter
value) that is closer to the base case than the condition
(parameter value) of the current function call
• Each invocation of the function gets its own set
of arguments and local variables
7/28/09
Recursion Example
/* print an integer in decimal
** K & R page 87 (may fail on largest negative int) */
#include <stdio.h>
void printd( int n )
{
if ( n < 0 )
{
printf( “-” );
n = -n;
}
if ( n / 10 )
printd( n / 10 );
/* (n / 10 != 0) -- more than 1 digit */
/* recursive call: n has 1 less digit */
printf( “%c”, n % 10 + ‘0’); /* base case --- 1 digit */
}
7/28/09
A Simple C Program
/* convertTemps.c */
#include <stdio.h> /* includes prototype for printf, etc */
typedef double Temperature;
/* prototype for CtoF */
Temperature CtoF( Temperature degreesCelsius);
int main( )
{
int temp;
for (temp = 0; temp < 100; temp += 20)
printf(“%2d degrees F = %5.2f degrees C\n”,
temp, CtoF( temp ));
return 0;
}
/* converts temperature in Celsius to Fahrenheit */
Temperature CtoF(Temperature celsius)
{
Temperature fahrenheit;
fahrenheit = 9.0 / 5.0 * celsius + 32;
return fahrenheit;
}
Typical C Program
includes
defines, typedefs, data
type definitions, global
variable declarations
function prototypes
main()
function definitions
7/28/09
#include <stdio.h>
typedef double Temperature;
Temperature CtoF( Temperature celcius);
int main( )
{
int temp;
for (temp = 0; temp < 100; temp += 20)
printf(“%2d degrees F = %5.2f degrees C\n”,
temp, CtoF( temp ));
return 0;
}
/* converts temperature in Celsius to Fahrenheit */
Temperature CtoF(Temperature celsius)
{
Temperature fahrenheit;
fahrenheit = 9.0 / 5.0 * celsius + 32;
return fahrenheit;
}
Compiling on Unix
Traditionally the name of the C compiler that comes
with Unix is “cc”.
On the UMBC GL systems, use the GNU compiler
named “gcc”.
The default name of the executable program that is
created is a.out
unix>
7/28/09
gcc convertTemps.c
Compiler Options
• -c
– Compile only (create a .o file), don’t link (create an executable)
gcc -c convertTemps.c
• -o filename
– Name the executable “filename” instead of a.out
gcc -o project1 convertTemps.c
• -Wall
– Report all warnings
gcc -Wall convertTemps.c
• -ansi
– Force adherence to the C ANSI standards
gcc -ansi convertTemps
• Use them together
gcc -ansi -Wall -o project1 convertTemps.c
1/13/10
Header Files
• When a file contains functions to be reused in several
programs, their prototypes and important #defines are
usually placed into a header ( .h ) that is then #included
where needed.
• Each .h file should be “stand alone”. That is, it should and
#defines needed by the prototypes and #include any .h
files it needs to avoid compiler errors.
• In this example, the prototype for CtoF() would be placed
into the file CtoF.h which would then be #included in
convertTemps.c or any other .c file that used CtoF( )
• The code for CtoF( ) would be placed int CtoF.c
7/28/09
CtoF.h
/* CtoF.h */
/* #includes needed by prototypes */
/* relevant #defines */
/* relevant typedefs */
typedef double Temperature;
/* prototype for functions defined in CtoF.c */
Temperature CtoF( Temperature celsius );
7/28/09
CtoF.c
/* CtoF.c */
/* necessary #includes, #defines */
#include “CtoF.h”
/* converts temp in Celsius to Fahrenheit */
Temperature CtoF(Temperature celsius)
{
Temperature fahrenheit;
fahrenheit = 9.0 / 5.0 * celsius + 32;
return fahrenheit;
}
7/28/09
convertTemps.c revisited
#include <stdio.h>
#include “CtoF.h”
/* note angle brackets */
/* note quotes
*/
int main( )
{
int temp;
for (temp = 0; temp < 100; temp += 20)
printf(“%2d degrees F = %5.2f degrees C\n”,
temp, CtoF( temp ));
return 0;
}
7/28/09
Compiling and linking
• When a program’s code is separated into multiple
.c files, we must compile each .c file and then
combine the resulting .o files to create an
executable program.
• The files may be compiled separately and then linked
together. The -c flag in the first two command tells gcc to
“compile only” which results in the creation of .o (object)
files. In the 3rd command, the presence of .o extension
tells gcc to link the files into an executable
gcc -c -Wall -ansi convertTemps.c
gcc -c -Wall -ansi CtoF.c
gcc -Wall -ansi -o myProgram convertTemps.o CtoF.o
• Or it can be done all in one step
– gcc -Wall -ansi -o myProgram convertTemps.c CtoF.c
1/20/10
Java/C Project example
• Number Theory - a problem about integers
• http://www.cs.umbc.edu/courses/undergradaute/3
13/fall09/code/numbertheory.txt
7/28/09
Download