tags:
- compsci/COMP1511/1
topic: C
date: 2023-12-16
Output
C is a low-level, general purpose programming language, and is ideal for usage in embedded systems and operating systems as a result of not having memory management built-in. In essence, the programmer has direct memory access. [1]
#include<stdio.h>
int main(void) {
printf("Hello, world!\n");
return 0;
}
#include <stdio.h>
This is similar to an import
statement in Python, but the library being imported - the Standard Input Output Library - is the barebones for any basic program, allowing text to be outputted to the terminal.
#int main(void){ }
This is a function, the code of which is enclosed within the parentheses. All code in C must be within functions (and functions cannot be nested within each other).
int
represents the data type of the function output (integer).main
represents the name of the function.(void)
represents the function input (in this case, none as it doesn't take input)printf("Hello, world\n");
Prints "Hello, world!" to the terminal. As C does not automatically include a trailing newline, a \n
must be manually added at the end of the function.
return 0;
This stops the program and returns the exit code '0' (True), indicating a successful execution. Note that in Python (on the other hand), 0 evaluates to False.
One of the distinguishing features of C from Python is that C programs need to be compiled before the code can actually be executed. In contrast, Python programs are simply interpreted
One of the more common C compilers on Windows is GCC (GNU Compiler Collection). A port of GCC is included as a part of MinGW[2] as part of an effort to port these tools to Windows (as opposed to the native environment of Linux). This is a helpful guide on how to install GCC on Windows, to be used with Visual Studio Code.
programname.c
and add whatever code is required. gcc programname.c -o myprogram.exe
.\myprogram.exe
-o
A flag representing that the code should be written to a file named myprogram.exe
.\myprogram.exe
The .\
indicates that the file should be run from the current working directory, as without it (and if myprogram.exe
does not exist in the current working directory) the following error would be produced.
[...] The term 'myprogram.exe' is not recognized as the name of a cmdlet, function [...] Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\myprogram.exe" for more details.`
Variables in C need to have their data type specified (declared), and each data type has a specified number of bytes in memory allocated to it.
If this byte number is exceeded, then overflow occurs (where the term integer overflow, and the Year 2038 problem[3] comes from )
These are some of the more common data types in existence.
Data Type | Description | Format |
---|---|---|
int :: |
A whole number. Takes 4 bytes (32 bits), allowing |
%d |
char :: |
A single character, wrapped in single quotes like so: 'a' Takes 1 byte, allowing a range of values from -128 to 127 (these are the ASCII values), as each character is associated with an integer in that range. The negative values typically represent special characters, such as trademark and copyright.[4] |
%c |
double :: |
A floating point number, meaning that a decimal point is present. Takes 8 bytes (64 bits) or double the size of integers. |
%lf |
(Note: int
is not always 32-bit, as in smaller embedded systems they can be 16 bit instead. int
are at a minimum 16-bit)
Arithmetic operations work similarly to real life; however, some quirks with data types can influence the results of such operations.
In division, the output of an operation is reliant on the data types used.
#include <stdio.h>
int main(void){
int int1 = 4;
int int2 = 10;
double mydouble = 2.0;
int_div = (int2/int1);
dou_div = (int1/mydouble);
printf("The result of the integer division is %d\n", int_div); // Prints 2
printf("The result of int/ddouble division is %lf\n", dou_div); // Prints 2.000000
}
Variables are declared like so:
#include <stdio.h>
int main(void){
int mynumber; // Declaration
mynumber = 5; // Initialisation
char mychar;
mychar = 'a';
double mydouble;
mydouble = '6.02';
return 0
}
They can be reassigned as necessary.
char mychar = 'a';
mychar = 'b';
The declaration and initialisation steps can also be merged, like so:
char mychar = 'a';
Variables printed to the terminal still need to be formatted like python; however, it is more similar to .format()
rather than f-strings. Format specifiers specify the data type of the variable, and start with a percent sign (%
)
#include <stdio.h>
int main(void){
int mynumber = 14;
char mychar = 'e';
printf("%d is my number. \n", mynumber);
printf("Here's my number: %d \n Here is the ASCII value of the letter %c: %d\n", mynumber, mychar, mychar);
}
Because char
values are associated with integers, mychar
can be converted into its ASCII form by formatting it as an integer (%d
).
See Data Types for the format specifiers associated with the introduced data types.
Constants can be defined at the beginning of the file, before main(void){}
. Like Python, they are stylised in capital letters to indicate that it is a constant.
#include <stdio.h>
#define MEANING_OF_LIFE 42
#define HOURS_IN_EARTH_DAY 24
The scanf()
function reads input from the user, and also requires format specifiers in the same way as the printf()
function.
This also means that variables are needed for both: output variables (the value of which it will output) and input variables (to where it will save the input). A &
'prefix' is required to tell the function where in the memory the input is to be saved to.
As a function, scanf()
returns the number of input values being scanned.
#include <stdio.h>
int main(void){
double mydouble;
printf("Enter a number: ");
scanf("%lf", &mydouble);
}
There are also differences in how whitespace is interpreted between data types. Notably, scanning int
ignores the white space and scanning char
does not. Ignoring whitespace with char
is possible by simply placing prefixing the %c
with a space.
scanf(" %c", &mychar);
With C, single and double quotes are not interchangeable. Single quotations hold characters, whereas double quotes represent string literals.
Identifying C code elements
Constructing a working program.
It's finally time to program!
You'll be building up to a program that can print out the following:
~ ~ 0 0 o -
Now let's modify what we just printed above to instead print out the following:
~ ~ 0 0 o \_/
#include <stdio.h>
int main(void){
printf(" ~ ~\n 0 0\n o\n -\n");
// modified version
printf(" ~ ~\n 0 0\n o\n \\_/\n");
return 0;
}