3. Programming in C

3.1. Variables

A variable is a name given to a storage area that programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

Standard data types for C programming (typical values):

Integer types:

Datatype

Size

Range

signed char

1 Byte

-128 … 127

unsigned char

1 Byte

0 … 255

unsigned short

2 Bytes

0 … 65535

signed short

2 Bytes

-32768 … 32767

unsigned int

4 Bytes

0 \dots 2^{32}-1

signed int

4 Bytes

-2^{31} \dots 2^{31}-1

unsigned long

8 Bytes

0 \dots 2^{64}-1

signed long

8 Bytes

-2^{63} \dots 2^{63}-1

Floating point types:

Datatype

Size

Range

Precision

float

4 Bytes

1.2E-38 … 3.4E+38

6 decimal places

double

8 Bytes

2.3E-308 … 1.7E+308

15 decimal places

Void type:

The void type specifies that no value is available. It is used in three kinds of situations:

  • A function with no return value has the return type as void.

  • A function with no parameter can accept a void.

  • A pointer of type void * represents the address of an object, but not its type.

Variables can be defined like this (examples):

  • int i, j, k;

  • char x = 'x';

3.2. Operators

The C language has different types of operators:

  • Arithmetic Operators, see below

  • Relational Operators, see below

  • Logical Operators, see below

  • Bitwise Operators, see below

  • Assignment Operators, e.g. =

  • Misc Operators, e.g. sizeof

Arithmetic operators

Operator

Description

Example

+

Adding

A + B = 30

-

Subtracting

A B = -10

*

Multiplication

A * B = 200

/

Division

B / A = 2

%

Modulus

B % A = 0

++

Increment value by one

A++ = 11

--

Decrement value by one

A-- = 9

Relational operators

Comparison

<, >, <=, >=

Equality

==

Inequality

!=

Logical operators

And:

&&

Or

||

Not

!=

Bitwise operators

Bitwise operators work on bits and perform bit-by-bit operation.

Binary And:

&

Binary Or

|

Binary XOR

^

Binary Left Shift

<<

Binary Right Shift

>>

3.3. Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

  • if statement: Consists of a boolean expression followed by one or more statements.

  • if…else statement: An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

  • switch statement: A switch statement allows a variable to be tested for equality against a list of values.

3.4. Loops

Loops are used if a block of code must be executed several times. It is possible to use one or more loops inside any other loop.

  • while loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

  • for loop: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

  • do…while loop: It is more like a while statement, except that it tests the condition at the end of the loop body.

Loop control statements change execution from its normal sequence.

  • break statement: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

  • continue statement: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

  • goto statement: Transfers control to the labelled statement.

3.5. Functions

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

The general form of a function definition in C programming language is as follows:

return_type function_name( parameter list )
{ body of the function }``

The return type specifies the data type of the value which is returned by the function, for example int. If no value is returned, the return type is void. The function name is the actual name of the function. The parameters act like a placeholder to pass values to the function. The function body contains the statements which define what the function does.

Example:

/* function returning the max between two numbers */
int max(int num1, int num2)
{
    /* local variable declaration */
    int result;

    if (num1 > num2)
    {
        result = num1;
    }
    else
    {
        result = num2;
    }

    return result;
}

To use the function, it must be called in the program. Therefore, the required parameters and the function name must be passed. If the function returns a value it must be stored in a variable.

/* calling a function to get max value */
ret = max(a, b);

Note

Variables inside a function or a block which are called local variables. Variables outside of all functions are called global variables. Variables in the definition of function parameters are called formal parameters.

3.6. Arrays

Arrays can store a fixed-size sequential collection of elements of the same type.

Declaration: type arrayName [ arraySize ];; example: double size[3];

Initialization: double size[3] = {10.0, 2.0, 3.4};

In this case, the number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

If the array should just big enough to hold the initialization, an empty square bracket is used: double size[] = {10.0, 2.0, 3.4, 9.4};

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array: timSize = size[2];. This will take the third element from the array and assign it to the variable “timSize”.

3.7. Pointers

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. It is used for example for dynamic memory allocation.

3.8. Strings

Strings are actually one-dimensional array of characters terminated by a null character ‘0’. Thus a null-terminated string contains the characters that comprise the string followed by a null.

Example: char word[] = "Hello";

3.9. Structures

Structures is a user defined data type available in C that allows to combine data items of different kinds. For example it might be helpful to track different information about a person like name, age and city.

Structures can be defined like this (structure tag is optional):

struct [structure tag]
{
    member definition;
    member definition;
    ...
    member definition;
}[one or more struct variables];

Example:

struct person
{
    char name[50];
    int age[25];
    char city[100];
};

/* Initialization */
struct person tim; /* Declare tim of type person */

/* Access member of structure */
timAge = tim.age;

To access any member of a structure, we use the member access operator (.).