---
# System prepended metadata

title: C Programming

---

C Programming
==

# Introduction to C

## A simple view of programming structure

![](https://i.imgur.com/3Tkm9GG.png)

- **Line 1~2 & 5 :**
    - Contents started with //means they doesn't have any effect on the programs. (They were just some comment to increase the readability of the program.)

- **Line 3:**
    - Context begins with the symbol # are processed by the preprocessor before the compilation. It tells the preprocessor to include the contents of the standard input/output header(stdio.h).

- **Line 4:**
    - Simply a blank line. It has no effect on the program but to easier the reading of the program.

- **Line 6:**
    - The declaration of main function. As the declaration of variable, we will have to declare the data type and define the name of the function before using them. In every C program, no matter how many function you have declared, we must no exclude the main function as it is the main body of your programming. (The detail of declaring a function will discuss later).

- **Line 7 & 9:**
    - The braces "{}" indicates that the context written in them should be considered the part of the **main** function.

- **Line 8:**
    - The main body of your C programming. Our program will follow each step you have writted in this part to execute the program.

## List of Escape Sequences

| Escape Sequence | Description |
| --------------- | ----------- |
| \n              | Newline. Position the cursor at the beginning of the next line.|
|\t               | Horizontal tab. Move the cursor to the next tab stop.|
|\a               | Alert. Produces a sound or visible alert without changing the current cursor position. |
|\\\              | Backslash. Insert a backslash character in a string. |
|\"               | Double quote. Insert a double-quote character in a string. |

## Variables and its definition

- **Define Variables Before They Are Used:**
    - All variables must be defined with a name and a data type before they can be used in a program. 
    - The C standard allows you to place each variable definition anywhere in **main** before that variable’s first use in the code (though some older compilers do not allow this). 
    - You’ll see later why you should define variables close to their first use.

- **Rules of defining the variable:**
    - A variable name in C can be any valid identifier.
    - An identifier is a series of characters consisting of letters, digits and underscores (\_) that does not begin with a digit.
    - C is case sensitive—uppercase and lowercase letters are different in C, so a1 and A1 are different identifiers.

- **Memory Concepts:**
    - The memory in the computer is an one-dimensional array.
        - ![](https://i.imgur.com/vpNSR2n.gif)
        - The website below shown how the data stored in the computer memory.
            - http://www.mathcs.emory.edu/~cheung/Courses/255/Syl-ARM/7-ARM/array-store.html
    - When we declare a random data type variable (for example ***int***), CPU will pick up a random location with a specific address to store your data. 

- **Rules of Operator Precedence:**
    - | Operator(s) | Operation(s) | Order of Evaluation (precedence) |
        | ------ | --------------- | ------------------- |
        | ()     | Parentheses     | Evaluated first     |
        |\*      | Multiplication  | Evaluated second    |
        |\/      | Division        |                     |
        |\%      | Remainder       |                     |
        |+       | Addition        | Evaluated Third     |
        |-       | Subtraction     |                     |
        |=       | Assignment      | Evaluated Last      |

- **Equality and Relational Operators:**
    - | Algebraic operators   | C operators | Meaning of C          |
        | ------------------- | ----------- |---------------------- |
        | $>$                 | >           | Greater than          |
        | $<$                 | <           | Smaller than          |
        | $\ge$               | >=          | Greater than or equal |
        | $\le$               | <=          | Smaller than or equal |
        | $=$                 | ==          | Equal to              |
        | $\ne$               | !=          | Not Equal to          |
        
---

# Structured Program Development in C

## Algorithms and Pseudocode
- **Algorithms:**
    - A procedure for solving a problem in terms of 
        - the actions to be executed, and;
        - the order in which these actions are to be executed;
    ![](https://i.imgur.com/r4lOUys.jpg)

- **Pseudocode:**
    - Pseudocode is an artificial and informal language that helps you develop algorithms.

## Control Structures
- Normally, statements in a program are executed one after the other in the order in which they’re written. This is called sequential execution. 
- Various C statements we’ll soon discuss enable you to specify that the next statement to be executed may be other than the next one in sequence. This is called transfer of control.

![](https://i.imgur.com/adCa3kO.jpg)

***\*Since the control structure in C and C++ is similar, we then use the diagram of control structure in C++ to show their relationship.***

## Selection Statements in C
- C provides 3 types of selection structures in the form of statements.
    - The "if" Selection Statements(**Single-selection statements**):
        - Suppose the passing grade on an exam is 60. Then the pseudocode statement will be 
        ![](https://i.imgur.com/o0iYj4M.png)

        - The preceding pseudocode If statement may be written in C as
        ![](https://i.imgur.com/GQwVlpB.png)
        
        - The flowchart illustrates the previous example.
        ![](https://i.imgur.com/y3d3vGJ.png)
        
    - The "if...else" Selection Statements (**double-selection statements**):
        - Using the previous example and add one more condition to it, we then have
        ![](https://i.imgur.com/JyCK3Ew.png)
        
        - The preceding pseudocode "**If...else**" statement may be written in C as
        ![](https://i.imgur.com/y0M2LhY.png)
        
        - The flowchart below illustrates the flow of control in the if...else statement.
        ![](https://i.imgur.com/tmGuXWV.png)
        
    - The "Switch" Multiple-Selection Statement
        - Suppose we want to collect the data of students' grades on their exam.
        ![](https://i.imgur.com/5BJUV1j.png)
        ![](https://i.imgur.com/1umEPU1.png)
        ![](https://i.imgur.com/Knehnn1.png)
        
        - You should be focus only on line 21~58, it show how a multiple-selection case work with "switch" operator.
            - Line 21: Similar to "if" statement, we should first mention the "switch" operator and put the variable we were concerning into the bracket "()". In this case, our target is the variable "grade".
            - Line 23 & 24: the "case" operator has the meaning similar to the "if" operator and the 'A' means that if the character inside the variable is A then the following steps will be executed.
            - Line 26: Although this step looked very wierd, but it is the most important step in the loop inside of the case (without it the loop will become infinity loop).
            - Line 53: The term default may also enlighten your vision that it is actually having the similar meaning to the "else" operator. For those variable didn't mentioned in the case operator above will enter this default loop.

## Iteration Statements in C
- An iteration statement allows you to specific that an action is to be repeated while some condition remains true. 
- ***The "while" Iteration Statement:***
    - Suppose we were trying to describe an iteration that occurs during a shopping trip. The pseudocode is as shown below:
    ![](https://i.imgur.com/9RnPoQM.png)
    
    - The appropriate code in C programming will be like:
    ![](https://i.imgur.com/mpKproi.png)
    
    - The flowchart is be like:
    ![](https://i.imgur.com/4qqOa35.png)

- ***The "do...while" Iteration Statement:***
    - The "do...while" iteration statement is similar to the while statement. In the while statement, the loop-continuation condition is tested at the beginning of the loop before the body of the loop is performed. The do...while statement tests the loop-continuation condition after the loop body is performed. Therefore, the loop body will always execute at least once.
    ![](https://i.imgur.com/QC46EVK.png)
    
---

![](https://i.imgur.com/vahbEA4.png)


---


- ***The "for" Iteration Statement:***
    - The for iteration statement handles all the details of counter-controlled iteration.
    ![](https://i.imgur.com/yUN5o4Q.png)

---

![](https://i.imgur.com/yDyCKSe.png)

---

    
## Iteration Control
- In order to exit to "while" loop, we will have to have the condition in the "while" statement to become false.
- Now we are trying to introduce 2 main method for the control of the iteration.
        
    1. **Counter-Controlled Iteration**
        
        - In this case, we first will have to setup an appropriate condition for the "while" condition. (Usually to have a variable in some range)
        - After that, setup a counter to be broken away from the range and then finally exit the "while" loop.
        ![](https://i.imgur.com/z4t4eTL.png)
        
    2. **Sentinel-Controlled Iteration**

        - From the example above, we may know that Counter-Controlled Iteration is actually suitable for iteration with known time-looping. That is, for example, we know there is only 10 result to be entered.
        - Sentinel-Controlled Iteration is suitable for those program must process an arbitrary number of looping.
        
        ![](https://i.imgur.com/qM9fTbg.png)
        - From the example, we may see that the "while" loop won't end unless the user type in the -1 value to the grade. Therefore, this iteration is actually ended by the user who inputting the data.

## Assignment Operators 

| Assignment operator | Sample expression | Explanation | 
| ------------------- | ----------------- | ----------- |
| +=                  | c+=7              | c=c+7       |
| -=                  | c-=4              | c=c-4       |
| \*=                 | c*=5              | c=c\*5      |
| /=                  | c/=3              | c=c/3       |
| %=                  | c%=9              | c=c%9       |

## Increment and Decrement Operators

| Operators | Sample Expression | Explanation |
| --------- | ----------------- | ----------- |
| ++        | ++a               | Increment a by 1, then use the new value of a in the expression in which a resides. |
|           | a++               | Use the current value of a in the pression in which a resides, then increment a by 1.|
| --        | --b               | Decrement b by 1, then use the new value of b in the expression in which b resides.|
|           | b--               | Use the current value of b in the expression in which b resides, then decrement b by 1.|

## "break" and "continue" statement 

- The break and continue statements are used to alter the flow of control.
- **"break" Statement:**
    - An operator may be used to exit immediately from any looping or selection statement.
    ![](https://i.imgur.com/2h6pSdT.png)
    
    - The figure above shows how a "break" statement works in C programming. The keypoint is in line 13~15.

- **The "continue" Statement:**
    - The continue statement skips the remaining statements in that control statement’s body and performs the next iteration of the loop. 
    ![](https://i.imgur.com/CWAqiQk.png)
    ![](https://i.imgur.com/pUc54XH.png)

## Logical Operators

- **AND operator(&&):**
    - Suppose we wish to ensure that two conditions are both true before we choose a certain path of execution.
    ![](https://i.imgur.com/Z2mIj53.png)
    
    - This "if" statement contains two simple conditions.

- **OR operator(||):**
    - Now let’s consider the "||"" (logical OR) operator. Suppose we wish to ensure at some point in a program that either or both of two conditions are true before we choose a certain path of execution. 
    ![](https://i.imgur.com/JeQNMkL.png)
    
- **Negation operator(!):**
    - C provides the ! (logical negation) operator to enable you to "reverse" the meaning of a condition. 
    ![](https://i.imgur.com/kynNr6e.png)
    
# Functions
- In order to make computer able to solve the real-world problem, we have to develop and maintain a huge program which is constructed from many smaller pieces. (Divide and Conquer)

## Modularizing Programs in C
- In C, there are 2 types of function available to used for modularizing program. 
    - **Prepackaged functions** in the C library such as printf(), scanf(),...
    - **Programmer-defined functions.**

### Headers

| Header     | Explanation |
| ---------- | ----------- | 
| <assert.h> | Contains information for adding diagnostics that aid program debugging.|
| <ctype.h>  | Contains function prototypes for functions that test characters for certain properties, and function prototypes for functions that can be used to convert lowercase letters to uppercase letters and vice versa. |
| <errno.h>  | Defines macros that are useful for reporting error conditions. |
| <float.h>  | Contains the floating-point size limits of the system. |
| <limits.h> | Contains the integral size limits of the system. |
| <locale.h> | Contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. The notion of locale enables the computer system to handle different conventions for expressing data such as dates, times, currency amounts and large numbers throughout the world. |
| <math.h>   | Contains function prototypes for math library functions.|
| <setjmp.h> | Contains function prototypes for functions that allow bypassing of the usual function call and return sequence.|
| <signal.h> | Contains function prototypes and macros to handle various conditions that may arise during program execution. |
| <stdarg.h> | Defines macros for dealing with a list of arguments to a function whose number and types are unknown. |
| <stddef.h> | Contains common type definitions used by C for performing calculations.|
| <stdio.h>  | Contains function prototypes for the standard input/output library functions, and information used by them.|
| <stdlib.h> | Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers and other utility functions.|
| <string.h> | Contains function prototypes for string-processing functions.|
| <time.h>   | Contains function prototypes and types for manipulating the time and date. |

### Math Library Functions
- In order to use the math library function, we should first include the math header by enter the the "#include<math.h>" in the very first of your program.

| Functions | Description                          | Example             |
| --------- | ------------------------------------ | ------------------- |
| sqrt(x)   | square root of $x$                   | sqrt(900.0) is 30.0 |
| cbrt(x)   | cube root of $x$                     | cbrt(27.0) is 3.0   |
| exp(x)    | exponential function $e^x$           | exp(1.0) is 2.71828 |
| log(x)    | natural logarithm of $x$             | log(2.71828) is 1.0 |
| log10(x)  | logarithm of $x$ with base 10        | log10(10.0) is 1.0  |
| fabs(x)   | absolute value of $x$ as a **float** | fabs(-13.5) is 13.5 |
| ceil(x)   | rounds $x$ to the smallest integer not less than $x$| ceil(9.2) is 10.0|
| floor(x) | rounds $x$ to the largest integer not greater than $x$ | floor(-9.8) is -10.0 |
| pow(x,y) | $x$ raised to power $y$| pow(2,7) is 128.0 |
| fmod(x,y) | remainder of $\frac{x}{y}$ as a **float** | fmod(13.657, 2.333) is 1.992 |
| sin(x) | trigonometric sine of $x$(in radians) | sin(0.0) is 0.0 |
| cos(x) | trigonometric cosine of $x$(in radians) | cos(0.0) is 1.0 |
| tan(x) | trigonometric tangent of $x$(in radians) | tan(0.0) is 0.0 |

### Programmer-defined Function

![](https://i.imgur.com/KJn2R7R.png)

- We should only focus the line 5, line 11 and line 17~21.
    - Line 5: Declaration of the function.
        - The **int** in parentheses informs the compiler that square expects to receive an integer value from the caller.
        -  The **int** to the left of the function name square informs the compiler that square returns an integer result to the caller.
    - Line 11: The main point is that using of the self-defined function "square(x)" to express the value of squared $x$.
    - Line 18~21: The keypoint is to define the function square which we have declared previously. The return statement in square passes the value of the expression $y*y$ (that is, the result of the calculation) back to the calling function.

### Function call
- Functions are invoked by a function call, which specifies the function name and provides information (as arguments) that the function needs to perform its designated task.
- A boss (the calling function or caller) asks a worker (the called function) to perform a task and report back when the task is done. For example, a function needing to display information on the screen calls the worker function printf to perform that task, then printf displays the information and reports back—or returns—to the calling function when its task is completed. The boss function does not know how the worker function performs its designated tasks. The worker may call other worker functions, and the boss will be unaware of this.

![](https://i.imgur.com/tj9UBUc.png)

### Function Call Stack and Stack Frame
- To understand how C performs function calls, we first need to consider a data structure known as a **stack**.
- **Stacks** are known as last-in, first-out (LIFO) data structures—the last item pushed (inserted) on the stack is the first item popped (removed) from the stack.

![](https://i.imgur.com/FywZlWT.png)
- Function call stack after the operating system invokes main to execute the program.

![](https://i.imgur.com/wVyoNd8.png)
- Function call stack after main invokes square to perform the calculation.

![](https://i.imgur.com/waFXwPZ.png)
-  Function call stack after function square returns to main.

### Variable in Functions
- Recall the declaration of variable in the view of computer is that sparing a memory with a specific address to store the data. 
- All variables defined in function definitions are local variables—they can be accessed only in the function in which they’re defined.

| Data types  | printf conversion specifier | scanf conversion specifier |
| ----------- | --------------------------- | -------------------------- |
| **floating-point types** |                |                            |
| long double              | %Lf            | %Lf                        |
| double                   | %f             | %lf                        |
| float                    | %f             | %f                         |
|**Integer types**         |                |                            |
| unsigned long long int   | %llu           | %llu                       |
| long long int            | %lld           | %lld                       |
| unsigned long int        | %lu            | %lu                        |
| long int                 | %ld            | %ld                        |
| unsigned int             | %u             | %u                         |
| int                      | %d             | %d                         |
| unsigned short           | %hu            | %hu                        |
| short                    | %hd            | %hd                        |
| char                     | %c             | %c                         |

### Storage Classes

- In C, the identifier(user-defined name for function or variable) has other attributes such as storage classes, storage duration, scope and linkage.
- Storage class specifier:
    - **auto** 
    - **register**
    - **extern**
    - **static**
- An identifier’s **storage duration** is the period during which the identifier exists in memory.
-  An identifier’s **scope** is where the identifier can be referenced in a program.
-  An identifier’s **linkage** determines for a multiple-source-file program whether the identifier is known only in the current source file or in any source file with proper declarations.
-  The storage-class specifiers can be split between **automatic storage duration** and **static storage duration**. Keyword **auto** is used to declare variables of automatic storage duration. Variables with automatic storage duration are created when program control enters the block in which they’re defined; they exist while the block is active, and they’re destroyed when program control exits the block.

-  ***Local Variable:***
    -  Only variable can have **automatic storage duration**. 
    -  A function's local variables (those declared in the parameter list or function body) normally have **automatic storage duration**.

- ***Static Storage Class:***
    - Keywords **extern** and **static** are used in the declarations of identifiers for variables and functions of static storage duration.
    - For ***static variables***, storage is allocated and initialized only once, before the program begins execution.
    - ***Local variables*** declared with the keyword **static** are still known only in the function in which they’re defined, but unlike ***automatic variables***, **static** ***local variables*** retain their value when the function is exited. The next time the function is called, the **static** ***local variable*** contains the value it had when the function last exited. 

### Passing Arguments by Value and by Reference.
- **Pass by Value:**
    - In this case, all the variable used in the function will have no effect on the variable outside of the function. The function will just simply return the value of the result to the output of the function.
- **Pass by Reference:**
    - In this case, all the variable changed within the calculation of the function will be affected including the variable declared outside of the function body.

# Arrays 
- Arrays are data structure consisting of related data items of the same type.
![](https://i.imgur.com/cFg0z02.png)

## Defining Arrays

![](https://i.imgur.com/GPAHkdR.png)

- Similar to declaration of a simple variable, we should first consider the data type of the variable.
- Next, we have to define the name of the array similar to a simple variable.
- After that, this is the most different point with variable, we have to declare the size of the array.
- In this Chapter, we will be focus on the array with data type of "**int**"  

## Array Example

![](https://i.imgur.com/PRwxmi2.png)
- The figure above shows that an initializing of elements of an array to all zeros and "**printf**" them out.

## Using Character Arrays to Store and Manipulate Strings

- ***Initializing with string:***
    - The following figure shows the initialization of the elements of array string1 to the individual characters in the string literal "first". In this case, the size of array string1 is determined by the compiler based on the length of the string. The string "first" contains five characters plus a special string-termination character called the null character. Thus, array string1 actually contains six elements. The escape sequence representing the null character is '\0'.
    ![](https://i.imgur.com/VVYk4xn.png)
    - Character arrays also can be initialized with individual character constants in an initializer list, but this can be tedious.
    ![](https://i.imgur.com/FDzrOxU.png)
    - As a string is exactly an array of characters, therefore we may access individual characters in a string directly using array index notation.
    - For example, for the string above we have string1[3]='s'.

- ***Inputting into a character Array***
    - To use scanf to input a string into a character array we have to use the conversion specifier "%s".
    - The name of the array is passed to "**scanf**" without the preceding & used with nonstring variables.
    ![](https://i.imgur.com/3n0VsCO.png)

- ***Outputting a  Character Array That Represents a String***
    - A character array representing a string can be output with "**printf**" and the "%s" conversion specifier. The array string2 is printed with the statement as below:
    ![](https://i.imgur.com/VI1yCTv.png)
    
## Static and Automatic Local Arrays

![](https://i.imgur.com/toiYw9o.png)
![](https://i.imgur.com/D1EuWQM.png)
![](https://i.imgur.com/aUlejAz.png)

## Passing Arrays to Functions
- Recall that all arguments in C are passed by value. C automatically passes arrays to functions by reference.
- The array’s name evaluates to the address of the array’s first element. Because the starting address of the array is passed, the called function knows precisely where the array is stored. Therefore, when the called function modifies array elements in its function body, it’s modifying the actual elements of the array in their original memory locations.
- Due to the reason above, there is a difference Between Passing an Entire Array and Passing an Array Element.
    ![](https://i.imgur.com/FbsTXad.png)
    ![](https://i.imgur.com/JY8gxjN.png)
    ![](https://i.imgur.com/d3llDN5.png)
- To prevent the modification of an array in the calculation within a function, we may use the "**const**" qualifier preceded the array parameter.

## Multidimensional Arrays
![](https://i.imgur.com/0ifH0EG.png)

### Initializing a Double-Subcripted Array 
![](https://i.imgur.com/W6PA43L.png)
- If there are not enough initializers for a given row, the remaining elements of that row are initialized to 0.
![](https://i.imgur.com/eAbJZyK.png)

# Pointer

- Pointers are variables whose values are memory addresses.
- Normally, a variable directly contains a specific value. 
- A pointer, however, contains an address of a variable that contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value. Referencing a value through a pointer is called indirection.
![](https://i.imgur.com/uNFx1qh.png)

## Declaring Pointers
![](https://i.imgur.com/E6chhbE.png)
- The definition specifies that variable "**countPtr**" is of type **int$^*$** and is read "**countPtr** is a pointer to **int**"

### Initializing and Assigning Values to Pointers 
- Pointers should be initialized when they’re defined, or they can be assigned a value. A pointer may be initialized to NULL, 0 or an address.

## Pointer Operators 
- The address operator (**&**):
    - A unary operator that returns the address of its operand. 
    ![](https://i.imgur.com/ZV8flnT.png)
    
    - The following statement assigns the address of the variable **y** to pointer variable **yPtr**. 
    - In this case, the variable **yPtr** is said to "point to" **y**. A schematic representation is shown below:
    ![](https://i.imgur.com/0i3SiL7.png)

- Pointer Representation in Memory
    ![](https://i.imgur.com/iN725t0.png)
    - Assuming that integer variable **y** is stored at location 600000, and pointer variable **yPtr** is stored at location 500000.

- The indirection operator (**\***):
    - The unary * operator, commonly referred to as the indirection operator or dereferencing operator, returns the value of the object to which its operand points.
    - For example, the statement below prints the value of variable **y(5)**.
    ![](https://i.imgur.com/z5dbSf6.png)

## Passing Arguments to Functions by Reference.
- Pass by Reference:
    - Declaration of Reference Variable:
        - ![](https://i.imgur.com/60c2J55.png)
        - Notice that in the context of "**int** &r=a", this is the declaration of the reference variable of "r" with initialization of assigning it to the variable "a".
    - Example of Reference Variable:
        - ![](https://i.imgur.com/Edy3l3M.png)
        - ![](https://i.imgur.com/BswdXQM.png)

- Example of Pass by Value
    - ![](https://i.imgur.com/rhWG5kp.png)

- Example of Pass by Reference(Pointer)
    - ![](https://i.imgur.com/6bteuV2.png)
    - ![](https://i.imgur.com/4k6Df7W.png)

- The **const** qualifier
    - Similar to the previous Chapter of "Function", to those variable which passed by reference and we wished not to modify their value during the calculation, we may use the **const** qualifier before the declaration of the parameter to prevent the modification of the variable during the calculation.





