Docsity

C and Java Variables and Data Types Comparison, Exams of C programming

Toggle sidebar
bg1
Chapter 1
Systems Programming and C Basics
What is in This Chapter ?
This first chapter of the course explains what Systems Programming is all about. It explains
how it is closely linked to the operating system. A few basic tools are explained for use with
the gcc compiler under a Linux Ubuntu environment running within a VirtualBox
application. It then introduces you to the C programming language in terms of the basic
syntax as it is compared to JAVA syntax. A few simple programs are created to show how to
display information, compute simple math calculations, deal properly with random
numbers, getting user input., using arrays and calling functions.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f

Partial preview of the text

Download C and Java Variables and Data Types Comparison and more Exams C programming in PDF only on Docsity!

Chapter 1

Systems Programming and C Basics What is in This Chapter? This first chapter of the course explains what Systems Programming is all about. It explains how it is closely linked to the operating system. A few basic tools are explained for use with the gcc compiler under a Linux Ubuntu environment running within a VirtualBox application. It then introduces you to the C programming language in terms of the basic syntax as it is compared to JAVA syntax. A few simple programs are created to show how to display information , compute simple math calculations , deal properly with random numbers , getting user input ., using arrays and calling functions.

1.1 Systems Programming and Operating Systems In COMP1405 and COMP1406, you developed various programs and applications. The goal was to write programs that “accomplished” something interesting in that it provided a service for the user … usually resulting in an “app” that interacted with the user. Examples of common applications are internet browsers, word processors, games, database access programs, spreadsheets, etc.. So, what you have been doing in your courses has been:

Applications Programming is the programming of software to provide

services for the user directly. Systems Programming , on the other hand is different. It has a different focus … and can be defined as follows:

Systems Programming is the programming of software that provides services

for other software … or for the underlying computer system. #include <stdio.h> int main() { printf( "Hello world\n" ); return 0 ; }

The goal of writing systems software is to make efficient use of resources (e.g., computer memory, disk space, CPU time, etc..). In some cases, performance may be critical (e.g., like a fast game engine). In fact, it is often the case that small improvements in efficiency can save a company a lot of money. Therefore, in this course, we will be concerned about writing efficient code … something we didn’t focus on too much in COMP1405/1406. In this course, we will also be trying to get a better grasp of the computer’s operating system.

An Operating System is system software that manages computer hardware and

software resources and provides common services for computer programs. Operating systems are the layer of software that sits between the computer’s hardware and the user applications. It is considered the “boss” of the computer … as it manages everything that is going on visibly, as well as behind the scenes. Some operating systems provide time-sharing features that schedule tasks at various times depending on how the computer’s resources (e.g., memory, disk storage, printers and devices) are allocated at any different time. There are various operating systems out there of which you may have heard of:

  • Windows
  • Mac OSX
  • Unix
  • Linux
  • Android
  • Chrome OS The operating system acts as the intermediary between the applications and the computer’s resources. Applications perform system calls to gain access to the resources: So, in a sense, the operating system provides services for the applications. It provides some core functionality to users as well as through programs. Here is some of the functionality that is provided by the operating system, although there is a lot more than this:

File I/O

  • provides file system organization and structure
  • allows access to read and write files
  • provides a measure of security by allowing access permissions to be set

Device I/O

  • allows communication with devices through their drivers
  • e.g., mouse, keyboard, printer, bluetooth, network card, game controllers…
  • manages shared access (i.e., printer queue)

Unix-based operation systems:

  • free … open source
  • a more open system that allows broad access to OS functions o "root" or super-user can do anything (extremely dangerous)
  • family of options (Linux, Solaris, BSD, Mac OS X, many others)
  • OS of choice for complex or scientific application development The language of choice for programming Unix-based operating systems is C.
  • closer to hardware
  • used to write Unix OS, device drivers
  • very fast, with negligible runtime footprint 1.2 Tools for Systems Programming We will now discus 4 tools that are essential for systems programming: Shells

A Shell is a command line user interface that allows access to an operating system’s

services. A shell allows the user to type in various commands to run other programs. It also serves as a command line interpreter. Multiple shells can be run at the same time (in their own separate windows). In Unix, there are three major shells:

  • sh - Bourne shell
  • bash - Bourne-again shell (default shell for Linux)
  • csh - C shell The shells differ with respect to their command line shortcuts as well as in setting environment variables.

A shell allows you to run programs with command line arguments (i.e., parameters that you can provide when you start the program in the shell). The parameters (a.k.a. arguments or options) are usually preceded by a dash – character. There are some common shell commands that you can make use of within a shell:

  • e.g., alias , cd , pwd , set , which There are some common system programs that you can make use of within a shell:
  • e.g., grep , ls , more , time , sort You can even get some help by accessing a kind of “user manual” through access of what are called man pages with the man command. We will make use of various shell commands and programs throughout the course. Text Editors

A Text Editor is a program that allows you to produce a text-based file.

There are a LOT of text editors out there. They are basic. Some are built into standard Operating System packages. There is a big advantage to knowing how to use one of these common editors … as they are available on any machine. It is good to choose one and “stick with it”, as you will likely develop an expertise with it. There are some common ones such as: vi / vim , emacs and gedit. You will need to use one for writing your programs in this course and for building make files (discussed later). There is a bit of a learning curve for these editors, as they all require you to use various “hot keys” and commands in order to be quick and efficient at editing. The commands allow you to write programs without the use of a mouse … which is sometimes the case on some systems when you don’t have device drivers working/installed.

  • It allows you to investigate what is happening in your program o can view your variables in the midst of your program o can observe the control flow of your program to find out whether certain methods are being called and in what order The goal is always to debug … to find out where your program is going wrong or crashing.

The command for using the compiler is gdb. You use it to run the program … after it has

been compiled. However, to use it, the program must have already been compiled with the - g option. When using the debugger, there are various commands that you can apply such as run , break , display , step , next and continue. 1.3 Writing Your First C Program The process of writing and using a C program is as follows:

  1. Writing: write your programs as .c files.
  2. Compiling: send these .c files to the gcc compiler, which will produce .o object files.
  3. Linking: the .o files are then linked with various libraries to produce an executable file.
  4. Running: run your executable file. Getting your C programs to run requires a little more work than getting a JAVA program to run. As with JAVA, your source code must be compiled. Instead of producing .class files, the C compiler will produce .o files which are called object files. These object files are “linked” together, along with various library files to produce a runnable program which is called an executable file. This executable file is in machine code that is meant to be run on a specific computer platform. It is not portable to other platforms.

Our First Program The first step in using any new programming language is to understand how to write a simple program. By convention, the most common program to begin with is always the "hello world" program which when run ... should output the words "Hello World" to the computer screen. We will describe how to do this now. In this course, you will use either emacs , vim or gedit to write your programs. I will be using examples that make use of gedit. Once you have your Terminal window open (you will learn how to do this in the first tutorial), then you start up your editor by specifying the editor name followed by the name of the file that you want to write … in this case it will be helloWorld.c. You use the & symbol at the end of the command line to indicate that you want to run the editor in the background. This allows you to keep the editor open while you are compiling and running/testing your code. If you don’t use the & character, then you must close the gedit editor in order to continue to work again in the Terminal window. Of course, you can always work with a second Terminal window if you’d like, but it is easiest to simply run the editor in the background. student@COMPBase : ~ $ gedit helloWorld.c & Here is a window that shows the editor with some code in it:

  1. The procedure for printing is simply printf() , where we supply a string to be printed … and also some other parameters as options (more on this later). If we want to ensure that additional text will appear on a new line, we must make sure that we include the \n character inside the string.
  2. The main() function should return an integer. By convention, negative numbers (e.g.,
    1. should be returned when there was an error in the program and 0 when all went well. However, by allowing a variety of integers to be returned, we can allow various error codes to be returned so as to more precisely what had gone wrong.
  3. Finally, notice that C uses braces and semi-colons in the same way that JAVA does. So ... to summarize, our C programs will have the following basic format: #include <…> #include <…> #include <…> int main() { ; ; ; } You should ALWAYS line up ALL of your brackets using the Tab key on the keyboard. Now that the program has been written, you can compile it in the same Terminal window by using the gcc -c command as follows: student@COMPBase : ~ $ gedit helloWorld.c & student@COMPBase : ~ $ gcc -c helloWorld.c student@COMPBase : ~ $ This will produce an object file called helloWorld.o. You can view the file by using the ls command: student@COMPBase : ~ $ gedit helloWorld.c & student@COMPBase : ~ $ gcc -c helloWorld.c student@COMPBase : ~ $ ls helloWorld.c helloWorld.o student@COMPBase : ~ $ Then, we need to link it (with our other files and standard library files) to produce an executable (i.e., runnable) file. We do this as well with the gcc -o compiler as follows: student@COMPBase : ~ $ gedit helloWorld.c & student@COMPBase : ~ $ gcc -c helloWorld.c student@COMPBase : ~ $ ls helloWorld.c helloWorld.o student@COMPBase : ~ $ gcc -o helloWorld helloWorld.o student@COMPBase : ~ $

After the -o is the name of the file that we want to be the runnable file. We follow it with a list of all object files that we want to join together. In this case, there is just one object file. This will produce an executable file called helloWorld. You can view the file by using the ls command: student@COMPBase : ~ $ gedit helloWorld.c & student@COMPBase : ~ $ gcc -c helloWorld.c student@COMPBase : ~ $ ls helloWorld.c helloWorld.o student@COMPBase : ~ $ gcc -o helloWorld helloWorld.o student@COMPBase : ~ $ ls helloWorld helloWorld.c helloWorld.o student@COMPBase : ~ $ You can then run the helloWorld file directly from the command line, but we need to tell it to run in the current directory by using ./ in front of the file name: student@COMPBase : ~ $ gedit helloWorld.c & student@COMPBase : ~ $ gcc -c helloWorld.c student@COMPBase : ~ $ ls helloWorld.c helloWorld.o student@COMPBase : ~ $ gcc -o helloWorld helloWorld.o student@COMPBase : ~ $ ls helloWorld helloWorld.c helloWorld.o student@COMPBase : ~ $ ./helloWorld Hello World student@COMPBase : ~ $ Notice that when you run your program, any output from the program will appear in the shell window from which it has been run. As a side point, you can link the files without first compiling. The linking stage will compile first by default: student@COMPBase : ~ $ gcc -o helloWorld helloWorld.c student@COMPBase : ~ $ 1.4 C vs. Java C code is very similar to JAVA code with respect to syntax. Provided here is a brief explanation of a few of the similarities & differences between the two languages. To begin, note that commenting code is the same in C as it is in JAVA: Commenting in C and JAVA // single line comment /* a multiline comment which spans more than one line. */

too small, and the number has more digits than the specified width … the width parameter will not affect the output. Here are some examples: printf(" %5d ", 256 ) // 256 printf(" %5f ", 3.14159265359 ) //3.141593 ... No effect printf(" %5c ", 65 ) // A printf(" %5s ", "Hello" ) //Hello printf(" %d ", 256 ) // 256 printf(" %f ", 3.14159265359 ) // 3.141593 printf(" %c ", 65 ) // A printf(" %s ", "Hello" ) // Hello The precision parameter works differently depending on the value being used. When used with floating point flag f it allows us to specify how many digits we want to appear after the decimal place. When used with floating point flag g it allows us to specify how many digits in total we want to be used in the output (including the ones to the left of the decimal): printf(" %2f\n ", 3.14159265359 ); //3.142 ... rounds up printf(" %2g\n ", 3.14159265359 ); //3.14 printf(" %2f\n ", 3141592.65359 ); //3141592.654 printf(" %2g\n ", 3141592.65359 ); //3.14e+ When used with string flag s , the precision parameter allows us to indicate how many characters will be displayed from the string: printf(" %2.1s\n ", "Hello" ); // H printf(" %2.3s
n
", "Hello" ); //Hel printf(" %2.5s\n ", "Hello" ); //Hello printf(" %10.1s\n ", "Hello" ); // H printf(" %10.3s\n ", "Hello" ); // Hel printf(" %10.5s\n ", "Hello" ); // Hello When used with integer, unsigned integer, octal and hexadecimal flags d, u, o, x, X , the precision parameter allows us to indicate how many leading zeros will be displayed: printf(" %6X\n ", 250 ); // FA printf(" %6X\ n ", 250 ); // FA printf(" %6X\n ", 250 ); // 0FA printf(" %6X\n ", 250 ); // 00FA printf(" %6X\n ", 250 ); // 000FA printf(" %6d\n ", 250 ); // 250 printf(" %6d\n ", 250 ); // 250 printf(" %6d\n ", 250 ); // 250 printf(" %6d\n ", 250 ); // 0250 printf(" %6d\n ", 250 ); // 00250 printf(" %6d\n ", -250 ); //- 00250

  • 16 -

When used with integer, unsigned integer, octal and hexadecimal flags d, u, o, x, X , the flags parameter also allows us to indicate how many leading zeros will be displayed. When used with numbers, the 0 flag allows leading zeros to be inserted and the + allows a plus sign to be inserted for positive numbers (normally not shown): printf(" %6d\n ", 250 ); // 250 printf(" % 0 6d\n ", 250 ); //000250 printf(" %+6d\n ", 250 ); //

When used with numbers or strings, the - flag allows everything to be left-aligned: printf(" %-6d\n ", 250 ); // printf(" %-+6d\n ", 250 ); //+ printf(" %-.1s\n ", "Hello" ); //H printf(" %-.3s\n ", "Hello" ); //Hel printf(" %-.5s\n ", "Hello" ); //Hello There are more options than this, but we will not discuss them any further. You may google for more information. In C , there are 4 main primitive variable types (but int has 3 variations). Variables are declared the same way as in JAVA (except literal float values do not need the ‘ f ’ character). Variables in C Variables in JAVA int days = 15 ; char gender = 'M'; float amount = 21.3 ; double weight = 165.23 ; char age = 19 ; short int years = 3467 ; long int seconds = 17102397834 ; char hungry = 1 ; int days = 15 ; char gender = 'M' ; float amount = 21.3f; double weight = 165.23; byte age = 19 ; short years = 3467 ; long seconds = 17102397834 ; boolean hungry = true ; Interestingly, there are no booleans in the basic C language. Instead, any value which is non-zero is considered to be true when used in a boolean expression (more on this below). Also, char is used differently since it is based on ASCII code, not the UNICODE character set. So the valid ranges of char is -128 to +127 (more on this later). Fixed values / numbers are defined using the #define keyword in C as opposed to final. Also, the = sign is not used to assign the value. Typically, these fixed values are defined near the top of the program file. You should ALWAYS name them using uppercase letters with multiple words separated by underscore characters.

tired =! tired; // tired will now be 0 sick =! sick; // sick will now be 1 If it makes your code easier to read, you can always define fixed values for TRUE and FALSE that can be used in your programs: #define TRUE 1 #define FALSE 0 Then you can do things like this: char tired = TRUE; char sick = FALSE; There is also another kind of conditional operator called the ternary / conditional operator which uses the? and : character in sequence. It is a short form of doing an IF statement: tired? printf( "tired\n" ) : printf( "not tired\n" ); It does the same as this: if (tired) printf( "tired\n" ); else printf( "not tired\n" ); However, the ?: is often used to provide a returned value that can be used in a calculation: int hoursWorked = 45 ; int bonus = (hoursWorked > 40 )? 25 : 0 ; printf( "%d\n" , bonus); In C, the FOR and WHILE loops work the same way: FOR loops : WHILE loops : int total = 0 ; for ( int i= 1 ; i<= 10 ; i++) { total += i; } printf( "%d\n" , total); int speed = 0 ; int x = 0 ; while (x <= 100 ) { speed = speed + 2 ; x = x + speed; printf( "%d, %d\n" , speed, x); } There is also a DO / WHILE loop … in which the condition is checked at the end of the loop. This guarantees that the loop is evaluated at least once: DO/WHILE loops :

int speed = 0 ; int x = 0 ; do { speed = speed + 2 ; x = x

  • speed; printf( "%d, %d\n" , speed, x); } while (x <= 100 ); In the first-year courses, we were interested in getting our code working. In this course, however, we will also be interested in getting our code to run quickly and efficiently. One example of improving efficiency is to make use of the break and continue statements when doing loops. For example, here is code that determines all the prime numbers from 1 to 100,000 : #include <stdio.h> int main() { int isPrime; printf( "The prime numbers from 1 to 100,000 are:\n" ); for ( int i= 1 ; i<= 100000 ; i++) { isPrime = 1 ; // Assume that i is prime for ( int j= 2 ; j<i; j++) { if (i%j == 0 ) isPrime = 0 ; // if factor found, not prime } if (isPrime) printf( "%d\n" , i); } } The code goes through all the numbers i from 1 to 100,000 and then checks all values from 2 to i to see if they divide evenly into i. If they do, then i is not a prime number. The code took about 22 seconds to run in my virtual environment! However, we can speed this up drastically by using the break statement. Consider the program logic. In the case where i is 100 , for example … as we search in the inner FOR loop, we find immediately that 2 divides into 100 evenly, so 100 is not prime. The code, however, will continue to search through remaining numbers from 3 through 99. But this is pointless, because we have already determined that 100 is not prime. If we therefore insert a break statement when we find out that i was not prime, then we break out of that loop and don’t check the remaining numbers from 3 through 99.