Skip to content
UoL CS Notes

C Language Basics

COMP281 Lectures

Basic I/O

printf()

This function is used for output like so:

printf("I have %d modules this term\n", sum);

This string is then sent to the standard output (stdout).

Format Specifiers

Format specifiers start with a % and define the type and format of a value to substituted. Above we saw %d for an integer but they follow the following form:

%[flags][minimum-field-width][.precision]Type

The following types are supported:

Type Description Example Output
%c A single character. printf("%c", 'v') v
%s A string. printf("%s %s", "Hello", "there!") Hello there!
%d A decimal integer. printf("%d", 27) 27
%o An octal integer. printf("%o", 27) 33
%x A lowercase hexadecimal integer. printf("%x", 27) 1b
%X An uppercase hexadecimal integer. printf("%X", 27) 1B
%f A floating point number. printf("%f", 1.23) 1.23
%e A floating point number with scientific notation. printf("%e", 3.14) 3.14E+01
%% A % character. printf("%%") %

The following flags are supported:

Flag Description Example Output
- Left align the output of this placeholder. printf("|%3i|%-3i|",12,12); |·12|12·|
+ Pretends a plus for positive signed numeric types. printf("%+i",17); +17
` ` (space) Prepends a space for positive signed numeric types. printf("|% i|",12); |·12|
0 Prepend zeros when width is specified. printf("|%04i|",12); |0012|
# Include extra parts of data structures such as 0x for hex. printf("%#X",26); 0X1A

You can use the minimum-field-width like so:

printf("|%5s|","ABC");

/* Outputs: */
// |··ABC|
printf("|%-5s|","ABC");

/* Outputs: */
// |ABC··|

you can also use it with a runtime variable:

printf("|%-*s|",5,"ABC");

/* Outputs: */
// |ABC··|

Precision works differently for different types:

Description Example Output
For floating point numbers, it controls the number of digits printed after the decimal point. printf("%.3f",3.1); 3.100
If the number provided has more precision than is given, it will round. printf("%.3f",3.1415); 3.142
For integers, the precision controls the minimum number of digits printed. printf("%.3d",99); 099
For strings, the precision controls the maximum length of the string displayed. printf("%.3s\n","abcd" ); abc

Escape Sequences

The following escape sequences are available:

Sequence Description
\a Beep
\b Backspace
\f Form-feed (line printers)
\n Newline
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark

scanf()

This function is used to read in data from the standard input (stdin). We can use it like so:

scanf("<format string>, &variable);

The variable must have an ampersand & before it so that the address is passed to scanf().

Operators

The following types of operators were covered in the lectures:

  • Arithmetic
  • Relational
  • Logical
    • Short circuit evaluation is used so the whole expression may not be evaluated depending on the result of the first expression.
  • Bit-wise Operators
  • Assignment Operators

You can see examples of them starting at slide 25 of the slides.

There are also the following miscellaneous operators:

Operator Description
sizeof() Returns the size of a variable in bytes.
& Returns the memory address of a variable.
* Pointer to a variable.
?: Conditional expression.

Comments

You can write comments like so:

/* This is a comment */

/*
 * This is also
 * a comment.
 */

Comments like these may not be recognised:

// I am generally a comment.

Comment are recommended when using values instead of constants, so that we know what the value means.

Decision Making

if & else

You can write an if else condition like so:

#include <stdio.h>
int main(void)
{
	int var;
	printf("Enter a Number: ");
	scanf("%d", &var);
	if( var % 2 == 0 )
	{
		printf("You entered an Even Number.\n");
	}
	else
	{
		printf("You entered an Odd Number\n");
	}
	return 0;
}

Nested ifs are also possible.

Conditional Operator

You can use this structure to write an if statement and assignment in one line:

var = (<conditional_statement>) ? <true_block/expression> : <false_block/expression>

This code finds the max of three numbers using this technique:

#include <stdio.h>
int main(void)
{
	int a, b, c, max;
	printf("Enter three numbers: ");
	scanf("%d%d%d", &a, &b, &c);
	max = ( a > b ) ? a : b;
	max = ( max > c ) ? max : c;
	printf("Maximum value = %d\n", max);
	return 0;
}

switch Statement

You can use this structure when checking for many conditions. It takes an integer expression like so:

#include <stdio.h>
int main(void)
{
	int score1, score2;
	printf("Enter scores for two tests: ");
	scanf("%d%d", &score1, &score2);
	switch( (score1 + score2) / 2 / 10 )
	{
		case 10:
		case 9:
		case 8:
			printf("Distinction.\n");
		break;
		case 7:
		case 6:
			printf("First Division.\n");
			break;
		case 5:
			printf("Second Division.\n");
			break;
		case 4:
			printf("Pass.\n");
			break;
		default:
			printf("Fail.\n");
	}
	return 0;
}

break finishes the block and stops you falling through to the next case.

Prefix & Postfix Operators

  • Prefix Operators - Evaluate to the current value and then complete the operation.
  • Postfix Operators - Complete the operation and then evaluate to the result.