C Programming/Introduction

From Wikiversity
(Redirected from C/Introduction)
Jump to navigation Jump to search
Completion status: this resource has reached a high level of completion.

Objective[edit | edit source]

  • Understand and differentiate between hardware and software.
  • Understand how the computer executes software.
  • Understand the concept of compiling and compiler
  • Set up and compile a C program
  • Gain a small taste of C: Create your very first C program and run it

Lesson[edit | edit source]

Hardware & Software[edit | edit source]

The Personal Computer (PC)
1. Monitor
2. Motherboard
3. CPU (Microprocessor)
4. Main memory (RAM)
5. Expansion cards
6. Power supply unit
7. Optical disc drive
8. Hard disk drive (HDD)
9. Keyboard.
10. Mouse

A computer's system unit, also commonly known as the computer case, contains a CPU (Central Processing Unit) while it usually has a monitor, keyboard, and a mouse connected to it. The CPU does all of the the processing and is an important part of the computer. Without it, the computer wouldn't even be able to run. The monitor displays graphics on a screen, which is easy for the user to see. The monitor acts as visual output. The keyboard and the mouse act as user input. The computer uses this input for many things and you'll most likely get some kind of response because of it.

The computer uses all of this equipment to do its job. This equipment, called hardware, isn't the only thing that makes a computer run. With all of the hardware something else is still needed to bring the computer to life. The stuff that actually makes the computer do something is called software. Unlike hardware, software cannot be manipulated directly by the user. Usually, the user needs to use the computer to interact with the software.

The CPU processes the software and executes it appropriately. Software is made up of a lot of instructions which the CPU executes. We don't need to go in depth about the instructions, since they vary between CPU's. The important thing is that we know that there are instructions.

It is now understood that, if we want the computer to perform a task, we must first get the instructions first. How? We simply write them down and then turn them into executable code that the CPU can use. Just remember this, a computer program is a set of instructions (a "recipe") that defines the task to be performed.

Program Execution[edit | edit source]

Machine code is the computer's true language. Some would call it unreadable by human standards. However, it is digital poetry to the trained. Back when computer science was still in its infancy, all programs were written in machine language. Before screens and printers existed, the programmer laboriously entered into the computer the machine code for the program and then fed each instruction via some external device, such as punch cards or switches. This task of writing programs was extremely slow and prone to errors.

When a program is executed, the computer reads each instruction and performs the task associated with that instruction. Since each computer can vary in the type and amount of instructions it has, we won't focus too much on this topic. The important thing to know is C's ability to be cross-platform when creating code. This portability was the key to C's success.

Compiling and compiler[edit | edit source]

Machine code is basically a set of instructions that the computer can execute. Computers use binary as the format for storing information. Each number can either be a 1 or a 0; which could be represented as on and off. Thankfully, a new method of writing programs has replaced machine code; this is called assembly. Although this is pretty consistent to writing binary, assembly still gives the program some edge, leading to less wasted time. Still, coding in assembly was slow and error-prone. Higher-level programming languages started to appear. These made it easier for the programmer to write programs, efficiently and quickly. Some of these languages convert their code to assembly, which will come in handy later in the course. C, unlike a lot of new programming languages, converts its code to assembly where a new executable file is created.

A compiler is a piece of software which takes a number of files of source code (C code in this case) and converts into an executable file which you can run on your computer. Note that not every language is compiled - some are "interpreted" (read line-by-line as the code is executed), and some are a mix, using something called "bitcode" or "bytecode". The executable file produced by a compiler is in a language called machine code - normally a compiler also converts the code into assembly in-between, while trying to "optimize" it (make it faster and take up less RAM).

Understanding C[edit | edit source]

C is widely considered the lowest-level programming language, after assembly language and machine code. What this means is that C focuses much more on operations that work out exactly as they look - the logic used in the language is very similar to what the computer does. This differs from higher-level languages where list manipulation might be an option, whereas in C, you specify exact operations over a range of computer memory addresses to manipulate data in a specific way. This can either make things more or less intuitive for a person - sometimes you get weird results due to data types, and other times it can make processes easier. Generally, however, C is viewed as being more difficult as you puzzle through the correct way to do certain things, and make sure you avoid dangerous syntax errors. However, knowing C is reward enough for the effort of learning the language - it is useful, flexible, and above all - very, very fast.

Setting up to program in C[edit | edit source]

C compiler[edit | edit source]

Linux or Macintosh computer has a built-in C compiler with them. Linux comes with GCC (GNU Compiler Collection - previously named GNU C Compiler), whereas MacOSX comes with Clang, a compiler that acts as a frontend to the LLVM compiler. Apple provides for MacOSX the Xcode software, but it takes up a lot of disk space, so if you don't have a lot to spare, consider alternatives. For Linux there are also plenty of environments. For both OSes, I would recommend using Sublime Text (Sublime Text 3) (note that Sublime Text doesn't allow compilation within the application itself). If you use Windows, installing a compiler can be a hassle. It is a good idea to install a development environment on Windows too - and it may come with a compiler attached to it!

The terminal[edit | edit source]

The terminal is the main way a programmer interacts with a computer. On MacOSX, it is an app under the name "Terminal", and is also called "Terminal" on many Linux distros. On Windows, you can use "Command Prompt". Upon opening, you will see a prompt to enter a command. To enter a command, type in to the command and hit the Enter key. An important thing to take note of is the filesystem. Your computer only normally looks in the current directory for needed files. To change the current directory, you can use the cd command on MacOSX or Linux. You can use cd --help to get more info on doing this.

Compiling programs[edit | edit source]

The way this is done will depend on how you are developing. If you are using a development environment then it may offer a way to compile within the app. However, it is impossible to cover all of this - just note that the option will normally fall under "Build" or "Compile". The command for compiling from the command line on MacOSX or Linux, however, can be covered. On Linux, simply use the gcc command, with the names of source files that are to be compiled into a single executable, and specify an output with the -o option (you should probably use a .o ending for this file on MacOSX, or .elf or .o on Linux). On MacOSX, you can use either gcc or clang to use the Clang compiler, as gcc is automatically symlinked to clang - meaning that both will actually execute Clang. The options are almost exactly the same for the two compilers, and the differences irrelevant for most purposes. It is a good idea to run the command gcc --help so that you can see a list of compiler options. You can also look online for more information.

Syntax in C[edit | edit source]

The syntax of a programming language is a set of rules specifying the way(s) in which operations may be specified to be carried out by a computer. They restrict the ways in which one may specify calculation, and make sure that there can be no ambiguities in the way to interpret a given snippet of code.

Just like other programming languages, C defines a set of syntax to be followed so that the program and be compiled and executed successfully. The "must-have" syntax in every C program is ";" (the semicolon). Each block of any set of operations to be performed MUST end with a semicolon. Normally what happens is you will have some declaration or initialization or function call or assignment, and then before you can do your next set of calculations to reach an end effect upon whatever you want to change next, you will use a semicolon to break up the blocks. This may sound confusing, but when to use one is quite intuitive if you think about it as going after any chunk of grouped operations.

Let's head to the very first C program to have the first impression of their syntax.

A Taste of C[edit | edit source]

Here is the classic Hello World program written in C.

#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");
    return 0;
}

All C programs have the #include macro, the most common being #include <stdio.h>. What this macro really does is to tell the compiler, "Hey! Before you compile my program, just copy and paste the contents of stdio.h where I am!". This is used to include the contents of standard C libraries.

In C, code is cut up into little blocks of code called functions. Unless declared otherwise, the function main will be called first when the program starts. The center of any C program is the function main(). It is where the CPU first starts executing. Anything that needs to be excuted by the program must be called/done by main(), or one of the functions it calls.

Don't worry about the words int and void, they are special sizes that will be discussed in the later lesson.

Next thing to be noticed from this program is the curly brackets ({}), as a function starts and ends with them.

The printf() function, which is arguably the most used function in C, is used to display formatted text.

At the heart of our program is an instruction to write "Hello, World!" (followed by a newline character "\n") to standard out, which is usually the console. So what exactly is happening here ? First, we call, or invoke, the function printf(). We put the arguments we wish to pass to printf() within the parenthesis. In the code above, we only pass a single argument, the string "Hello, World!\n". What's a string? Don't worry, that and more will be explained in the following lessons.

On the next line, we have return 0. When the computer encounters return 0, it immediately exits the function, meaning nothing past it will be executed, and returns the integer 0 to the caller of the function (in this case, the OS). When a non-zero integer is returned to the OS, it is usually a sign that an error has occurred somewhere in the program.

You may have noticed the semi-colon (;) at the end of printf("Hello, World!\n") and return 0. These lines of code are called statements, and in C, statements are always terminated with a ;. If you do not terminate your statements, the computer will not know where the statement ends and the next one begins.

Try writing the source code above to a file. Save the file (remember to save it with the extension .c if you're using a plain-text editor) then compile it.

To execute/run the newly compiled program, from the terminal of MacOSX or Linux, simply type out the path to the file - eg. if it's in your Documents, type in ~/Documents/filename where filename is the name of the file. Alternatively, if the file is in the current directory your terminal is in (use cd --help to find out more), then use ./filename. Congratulations! You've now just executed your first program that you wrote!

Assignments[edit | edit source]

  • Name one piece of hardware that acts as user input.
  • Name one piece of hardware that acts as user output.
  • What is a computer program made up of?
  • What is the computer's true language?
  • What is the lowest-level, platform-dependent language called?
  • Is C compiled or assembled?
  • Were you able to compile the example in this lesson? If so, what happened?