程序代写代做代考 Excel Java compiler c++ CS402: Seminar 1

CS402: Seminar 1

A C and C++ Primer

In this session we are going to take a brief look at C and C++. The two
languages are quite similar in terms of syntax, and are often grouped together
when discussing various programming languages. We will start by looking at
basic C programs, and then cover some of the object-oriented features of C++.

1 Hello World

First things �rst, lets get up and running with the ubiquitous �Hello, world!�
program. Open up your favourite text editor (maybe vim or emacs), and type
in the following program, saving it as hello.c

#include

int main ( int argc , char* argv [ ] ) {
p r i n t f ( “Hel lo , world ! \ n” ) ;

return 0 ;
}

To compile this program, open up a terminal window and change to the directory
containing the program. Then use the GCC compiler like so:

gcc -o helloworld hello.c

You will notice a few di�erences between C and Java, but overall the structure
of the programs is mostly the same. One thing to notice is that you need to
put special characters like the line break (\n) at the end of strings you want to
print.
Run this program with:

./helloworld

2 A Few More Programs

This next program calculates factorials, demonstrating the use of functions and
for loops in C. In C, it is important that you de�ne your functions before you
use them. You can do this just by keeping them further up the �le, or you can
use prototype de�nitions that just state the return type, name, and arguments
of the function. The prototype of the factorial function would look like this:

int f a c t o r i a l ( int n) ;

1

Below is the factorial program:

#include

int f a c t o r i a l ( int n) {
int i = 0 ;
int f a c = 1 ;

for ( i = 1 ; i <= n ; i++) { f a c = fac * i ; } return f a c ; } int main ( int argc , char* argv [ ] ) { int f a c_f i v e = f a c t o r i a l ( 5 ) ; p r i n t f ( " 5 ! i s %d\n" , f a c_f i v e ) ; } Task 1 Write a program that uses the formula ◦C = 5 9 (◦F−32) to print a table of Farenheit temperatures, from 0 to 300 in steps of 20◦, with the corresponding temperatures in Celsius. The example output would be something like: 0 -17 20 -6 40 4 ... 300 148 3 A Few Pointers Pointers are the main di�erence between C and Java. What you really need to know is that pointers point to some location in memory. The simple program that follows introduces pointers. #include

int main ( int argc , char* argv [ ] ) {
int* pntr ;
int my_int = 6 ;

// Make pntr po in t to the l o c a t i on o f my_int
pntr = &my_int ;

// Write some pr in t s ta tements to check the va lue s
p r i n t f ( “The value o f my_int i s %d , the value o f pntr i s %p\n” ,

my_int , pntr ) ;

// What i s the va lue t ha t pntr i s po in t ing at ?
p r i n t f ( “Pntr i s po in t ing at %d\n” , *pntr ) ;

// We dere f e rence the po in t e r with the *
// to ge t at the va lue i t ‘ s po in t ing at

2

return 0 ;
}

When using pointers, adding a * to the beginning of the variable lets us get at
the value it contains. So if we have:

int a = 50 ;
int* a_pntr = &a ;

p r i n t f ( ” Pointer i s %x , the value i s %d\n” , a_pntr , *a_pntr ) ;

This �rst uses the & to set a_pntr to the address of a, and then uses * to get
at the value of a_pntr in order to print it out.

Task 2 To check your understanding of pointers, try writing a swap function
here that will swap the values of variables by using pointers. How can we pass
pointers to value_a and value_b into this function?

#include

void swap ( int* a , int* b) {
/* i n s e r t code here */

}

main ( int argc , char* argv [ ] ) {
int value_a = 50 ;
int value_b = 5 ;

/* use swap here , then pr in t the va lue s */
}

4 Allocating Memory

In C, we can declare arrays almost the same way we do in Java, using the square
braces, and some number of elements, like so:

int [ ] my_array = {10 , 11 , 12 , 14 , 15} ;

p r i n t f ( “The f i r s t element i s %d\n” , my_array [ 0 ] ) ;

/* Creating an array with space f o r 10 i n t e g e r s */
int x [ 1 0 ] ;

The problem with arrays in C is that we can’t declare a dynamically sized array
just using the square braces. So if we want to create an array of a given size,
passed in by the user for example, we need to use the malloc function to allocate
the memory for the array.
Malloc works with pointers, rather than the int[] style array declaration. This
is because the call to malloc will return a pointer to the �rst element. In order
to create an array, we do something like this:

3

int* my_malloc_array ;

/* 10 could be any number , or an in t e g e r v a r i a b l e */
my_malloc_array = ( int *) mal loc ( s izeof ( int ) * 10) ;

When you are done with memory, it must be deallocated so that it can be re-
used by the operating system. We deallocate memory using the free method
(continuing the above example):

f r e e (my_malloc_array ) ;

Task 3 Take a look at the following program. It reads in a series of integers
from the user, then prints them back out in reverse order. The problem is that
SIZE is hardcoded as 5. Your task is to modify this program in order to read
a dynamic number of integers. First ask the user how many ints they want to
enter, then read them in, then print them back out.

#include
#include

#define SIZE 5

int main ( ) {
int ar r [ SIZE ] ;
int temp ;
int i = 0 ;
while ( s can f ( “%d” , &temp) > 0) {

ar r [ i ] = temp ;
i++;

}
/* i now po in t s _past_ the l a s t element . */
/* Move i back to po in t at the l a s t e lement */
i−−; /* Point to l a s t */
for ( ; i >=0; i−−) {

p r i n t f ( “%d\n” , a r r [ i ] ) ;
}
return 0 ;

}

The scanf function reads an integer from the command line into some vari-
able, temp in this example. Note that you need to use the & to pass the address
of the variable to read the variable into.

5 Classes

Classes are the �rst exclusively C++ feature we will be looking at. Classes
provide a way of grouping functions and data, giving logical structure to our
programs. A C++ class is declared in a header �le, like so:

c l a s s C i r c l e {
pub l i c :

C i r c l e (double r ) ;
double getArea ( ) ;

4

double getCircumference ( ) ;
p r i va t e :

double rad iu s ;
stat ic const double PI ;

} ;

The basic class declaration consists of a number of variable and function de�ni-
tions, quali�ed with under either the public or private access modi�ers. The
Circle method is a constructor, so doesn’t require a return type.The most im-
portant thing to note about C++ classes is the ; after the closing brace. Type
this code into a �le, and save it as Circle.h.
We implement the methods de�ned in the class declaration in an �implementa-
tion� �le:

#include ” C i r c l e . h”

const double Ci r c l e : : PI = 3 . 1416 ;

C i r c l e : : C i r c l e (double r ) :
r ad iu s ( r )

{
}

double Ci r c l e : : getArea ( )
{

return PI* rad iu s * rad iu s ;
}

double Ci r c l e : : getCircumference ( )
{

return 2* rad iu s *PI ;
}

The implementation includes the header �le in which we de�ned the class, and
then provides de�nitions for all the functions we declared. Note the static
variable PI is also de�ned in this �le. The syntax after the constructor is known
as an initializer list, as is a way of assinging values to the instance variables of
the class. Save this �le as Circle.C.

5.1 Using Classes

Let’s try using our new Circle class with a simple example.

#include

#include ” C i r c l e . h”

int main ( int argc , const char* argv [ ] )
{

C i r c l e c1 ( 4 . 0 ) ;
s td : : cout << "Circumference o f c1 i s : " << c1 . getCircumference ( ) << std : : endl ; C i r c l e * c2 = new C i r c l e ( 2 . 5 ) ; s td : : cout << "Area o f c2 i s : " << c2−>getArea ( ) << std : : endl ; 5 de l e t e c2 ; } We start by including our header �le which contains the de�nition of the Circle class. We create the circle c1 using the constructor, and call one of the class methods using the . operator. When we create the second circle, c2, we use the new operator, which allocates memory and creates the object, and returns a pointer to the object. This is important because when an object is created on the heap in this way, the pointer can be passed around and the same object can be used by multiple functions. When calling functions on an object pointer, we use the -> syntax. This deferences the pointer and calls the correct method.
To delete the object when we are done, we use the delete keyword1. The �rst
circle was created on the stack, so will be destroyed automatically when it goes
out of scope. Save this �le as main.C, and let’s compile this example:

g++ -o circle_test Circle.C main.C

Try running the example to ensure you get the results you expect.

6 Debugging

It’s pretty likely that during the course of the assignment you will run into
some bugs in your program. Finding bugs in C and C++ programs can be
hard, mostly because of the notorious segfault. We will look at a few ways to
help debug your program:

1. Compile your code with the -g �ag, this will enable debugging symbols in
your code.

2. Load your program with gdb, the GNU Debugger, like so: gdb

3. Inside gdb, type run to run your program.

4. If your program segfaults, you should see some helpful information like
line number and function name.

6.1 What else can I do with gdb?

There are a few nifty things in gdb that will make your life easier.

� print will print out the value of a variable. If you try and
print something and see something like $1 = (int *) 0x0, then it prob-
ably means the variable (or pointer) has not been initialised.

� Placing breakpoints: inside gdb, break : will allow you to
set a break point at a particular line (just before your program crashes, for
example). Gdb will halt the program at the speci�ed line, and will allow
you to examine the values of variables, as well as set new breakpoints.

1
new and delete are the C++ equivalents of malloc and free.

6

� Backtraces provide information on the functions that have been called
when the program crashes. Try typing in bt to gdb when your program
crashes. You should see information on the function it was in, as well as
the path of functions leading up to the crash.

For more information on gdb, use the help command, or do some research
online. Hopefully this basic guide contains enough to keep you going with this
assignment.

7 Extra Resources

The main reference for C programming is Kernighan and Ritchie’s book, The
C Programming Language [1]. It is well worth getting hold of, both for it’s
excellent C content, and the fantastic example of technical writing.

C++ is a rich languange with a lot of depth, as such, there are a huge
number of C++ reference books. We like The C++ Programming Language [2]
and Programming: Principles and Practice Using C++ [3], two books written
by Bjarne Stroustrup, the creator of C++. If you already have some C++
experience, then Scott Meyer’s E�ective C++ [4] is a fantastic book of tips and
tricks for improving your code.

References

[1] Brian Kernighan & Dennis Ritchie, The C Programming Language, Prentice
Hall Professional Technical Reference, 2nd Edition, 1988.

[2] Bjarne Stroustrup, The C++ Programming Language, Addison-Wesley Pro-
fessional, 3rd Edition, 2000.

[3] Bjarne Stroustrup, Programming: Principles and Practice Using C++,
Addison-Wesley Professional, 1st Edition, 2008.

[4] Scott Meyers, E�ective C++: 55 Speci�c Ways to Improve Your Programs
and Designs, Addison-Wesley Professional, 3rd Edition, 2005.

7