C INTRODUCTION
1. Introduction
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’ll go through the basics and defining characteristics of both languages, discuss the tools required to compile and run source code, we’ll run through a few exercises, and at the end there are a few problems for you to test out your knowledge.
2. Remote Working
Copyright By PowCoder代写 加微信 powcoder
As you will be working remotely for this lab session, we recommend that you make use of the DCS managed Login/Remote nodes for completing the following lab exercises. This section will explain how to get started with the DCS nodes if you are unfamiliar with them, and how you can make use of them to run your C programs.
The first step is to connect to one of the DCS Login/Remote nodes using one of the following two commands (where uXXXXXXX is be replaced by your username and nn in remote-nn is replaced by the last two digits of your username):
When you have connected to one of the nodes, you will see that you can access all of the files that you have saved in your DCS file system. Next, load the neces- sary environment module for the compiler using the following command:
$ module load cs402-mpi
This will allow you to compile any programs that you write in this lab sheet using gcc or g++ (more information on compiling programs can be found in Sections 3.2 and 4 of this lab sheet).
A complete end-to-end toolchain is required to write, compile, and run (as well as debug) source code. The lab machines come with a variety of different programs for each step of the chain to suit you.
2 C INTRODUCTION
3.1. Text Editors. We’ll be writing the source code in all of these labs in a text editor and compiling and executing it in a terminal. Alongside the default programs that are part of the operating system on the lab machines (programs such as KWrite), an extensible program called Atom is also provided. Atom provides built-in syntax highlighting, plugin support, and a large suite of settings that make it great for writing source code. It’s accessible via the start menu/program launcher, or by typing atom into a terminal.
Other great options include vim or emacs as command-line, terminal-based text editors. These are equally as fully featured as Atom, they just don’t include a graphical interface. It’s up to you what you want to use – it’s entirely personal preference.
3.2. Compilers. There are two standard compilers1 for C and C++:
• gcc compiles C source code files.
• g++ compiles C and C++ source code files, and links against the C++
libraries.
It’s best to use gcc exclusively for C code, and g++ for C++ code, so as not to confuse things.
These are both executed by passing the name of your output file after the -o flag (which tells the compiler to compile, assemble, and link all source code files into one file) and place it into the filename you specified. After this, you type in the name of every source code file that you want to compile into your final program. In your terminal (assuming you’re cd’d into the directory with your files), it will look something like this with:
$ gcc -o
$ gcc -o abc a.c b.c c.c
C INTRODUCTION 3
After this has successfully executed, I can run it by typing in ./ followed by the name of my program, like so:
This will execute the compiled program abc and then return back to the terminal prompt once it has finished.
5. Exercises
Below are a series of exercises to get you familiar with the very basics of C and C++, compiling, and running programs. Please work through these sequentially, and then try the problems further down the sheet.
5.1. Hello World. First things first, let’s get up and running with the quintes- sential “Hello, world!” program. Open up your favourite text editor, and type in the following program, saving it as hello.c:
#include
int main(int argc, char* argv[])
printf(“Hello, world!\n”);
return 0; }
To compile this program, open up a terminal window and change to the direc- tory containing the program. Then use the GCC compiler like so:
$ gcc -o helloworld hello.c
You will notice a few differences 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
5.2. Further C. This next program calculates factorials, demonstrating the use of functions and for loops in C. In C, it is important that you define your functions before you use them. For now, you can do this by keeping them further up the file, or you can use prototype definitions that just state the return type, name, and arguments of the function at the top of the file (these can also go in a separate header (.h) file and you can #include them at the top, but we will just write the function towards the top of the file for now, as in the code below).
The prototype of the factorial function would look like this:
4 C INTRODUCTION
int factorial(int n);
Below is the factorial program for you to compile and run by yourself.
#include
int factorial(int n)
int i = 0, fac = 1;
for (i = 1; i <= n; i++)
fac *= i; }
return fac; }
int main(int argc, char* argv[])
int fac_five = factorial(5);
printf("5! is %d\n", fac_five);
You now know all you need to attempt Task 1.
5.3. Pointers. Pointers are the main difference between C and Java. What you really need to know is that pointers point to some location in memory. The following, simple program introduces pointers.
#include
int main(int argc, char* argv[])
int* pntr;
int my_int = 6;
// Make pntr point to the location of my_int
pntr = &my_int;
// Write some print statements to check the values
printf(“The value of my_int is %d, the value of pntr is %p\n”,
my_int, pntr);
// What is the value that pntr is pointing at?
printf(“Pntr is pointing at %d\n”, *pntr);
// We dereference the pointer with the *
// to get the value it’s pointing at
return 0; }
C INTRODUCTION 5
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;
printf(“Pointer is %x, the value of %d\n”, a_pntr, *a_pntr);
The first 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.
You now know all you need to attempt Task 2.
5.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};
printf(“The first element is %d\n”, my_array[0]);
// Creating an array with space for 10 integers
int x[10];
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 first element. In order to create an array, we do something like this:
int* my_malloc_array;
// 10 could be any number, or an integer variable
my_malloc_array = (int *)malloc(sizeof(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):
free(my_malloc_array);
You now know all you need to attempt Task 3.
5.5. Classes. Classes are the first exclusively C++ feature we will be looking at. Classes provide a way of grouping functions and data, giving logical structure to our programs. An example C++ class representing a circle is declared in a header file, like so:
class Circle {
Circle(double r);
double getArea();
double getCircumference();
C INTRODUCTION
double radius;
static const double PI;
The basic class declaration consists of a number of variable and function defi- nitions, qualified with either the public or private access modifiers. The Circle method is a constructor, so doesn’t require a return type. The most important thing to note about C++ classes is the ; after the closing brace. Type the above code into a file, and save it as Circle.h.
We implement the methods defined in the class declaration in a separate imple- mentation file. Below is an example implementation of the Circle class.
The implementation includes the header file in which we defined the class, and then provides definitions for all the functions we declared. Note the static variable PI is also defined in this file. The syntax after the constructor is known as an initialiser list, as is a way of assigning values to the instance variables of the class. Save the following code listing into a new file called Circle.cpp.
#include “Circle.h”
const double Circle::PI = 3.1416;
Circle::Circle(double r): radius(r) { }
double Circle::getArea()
return PI * radius * radius;
double Circle::getCircumference()
return 2 * radius * PI;
You now know all you need to attempt Task 4. 6. Problems
6.1. Task 1: Temperature Conversion. Write a program that uses the formula ◦C = 59(◦F −32) to print a table of Fahrenheit temperatures, from 0 to 300 (inclusive) in steps of 20◦, with the corresponding temperatures in Celsius. The example output would be something like:
C INTRODUCTION 7
6.2. Task 2: Swapping Using Pointers. To check your understanding of point- ers, 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) {
/* insert code here */
int main(int argc, char* argv[]) {
int value_a = 50;
int value_b = 5;
/* use swap here, then print the values */
6.3. Task 3: Dynamic Allocation. 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 argc, char* argv[])
int arr[SIZE];
int i = 0;
while (scanf(“%d”, &temp) > 0) {
arr[i++] = temp;
// i now points _past_ the last element
i–; // Move i back to point at the last element
for (; i >= 0; i–){
printf(“%d\n”, arr[i]);
return 0; }
8 C INTRODUCTION
The scanf function reads an integer from the command line into some variable (temp in this example). Note that you need to use the & to pass the address of the variable to read the variable into.
6.4. Task 4: Classes. In the same directory as the Circle.h and Circle.cpp, save the following code listing into a file called main.cpp.
#include
#include “Circle.h”
int main(int argc, const char* argv[])
Circle c1(4.0);
std::cout << "Circumference of c1 is: " <<
c1.getCircumference() << std::endl;
Circle* c2 = new Circle(2.5);
std::cout << "Area of c2 is: " <<
c2->getArea() << std::endl;
delete c2;
We start by including our header file which contains the definition 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 keyword2. The first circle was created on the stack, so will be destroyed automatically when it goes out of scope.
Compile these files together into a single executable with:
$ g++ -o circle Circle.cpp main.cpp
Execute with:
$ ./circle
Ensure your program compiles correctly and inspect the output to ensure that it prints what you expect.
2new and delete are the C++ equivalent of malloc and free from C.
C INTRODUCTION 9
Appendix A. 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. A notorious bug that is likely to occur is the infamous segmentation fault, or segfault. We will look at a few ways to help debug your program:
(1) Compile your code with the -g flag. This will enable debugging symbols in your code.
(2) Load your program (and associated inputs, if any) with gdb – the GNU debugger[2] – like so:
$ gdb
(3) Inside gdb, your program will be loaded but not automatically executed. Type run to start your program in the debugger:
(gdb) run
(4) If your program generates an error or segfaults, gdb will pause and provide you with some helpful information like line number and function name.
Being a general-purpose debugger, gdb is able to perform several tasks and inspections that make finding the root cause of the error simpler. These include:
• print
• break
• bt provides a backtrace on a failed execution of all of 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.
10 C INTRODUCTION
Appendix B. Additional Resources
The main reference for C programming is Kernighan and Ritchie’s book, “The C Programming Language”[3]. It is well worth getting hold of, both for its excellent C content, and it being a fantastic example of technical writing.
C++ is a rich language with a lot of depth, as such, there are a huge number of C++ reference books. We like “The C++ Programming Language”[4] and “Programming: Principles and Practice Using C++”[5], two books written by , the creator of C++. If you already have some C++ experience, then ’s “Effective C++”[6] is a fantastic book of tips and tricks for improving your code.
References
[1] GNU. GCC online documentation. https://gcc.gnu.org/onlinedocs/ (accessed December 10, 2019), 2019.
[2] GNU. GDB: The GNU Project Debugger. https://www.gnu.org/software/gdb/ (accessed December 9, 2019), 2019.
[3] and . The C Programming Language. Profes- sional Technical Reference, 2nd edition, 1988.
[4] . The C++ Programming Language. Addison- , 3rd edi- tion, 2000.
[5] . Programming: Principles and Practice Using C++. Addison- – fessional, 1st edition, 2008.
[6] s. Effective C++: 55 Specific Ways to Improve Your Programs and Designs. Addison- , 3rd edition, 2005.
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com