C Programming
This is a collection of notes on C Programming. This is a work in progress and will be updated regularly.
- 00. Introduction to C Programming
- 01. Arrays in C program
- 02. C Pointers
- 03. Conditional statements
- 04. Errors
- 05. Functions
- 06. Looping
- 07. Strings and Character array
- 08. Structure and Unions
00. Introduction to C Programming
Notes on C Programming
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of the C language include low-level memory access, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like an operating system or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from the C language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C language. C++ is nearly a superset of C language (Few programs may compile in C, but not in C++).
01. Arrays in C program
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
Collection of variables of the same type.
size and type of an array cannot be changed once it is declared.
Array values are stored in contiguous memory locations
Declaring Arrays
Syntax
Example
Initializing Arrays
Multi-dimensional Arrays
Example
Two-dimensional Arrays
A two-dimensional array is, in essence, a list of one-dimensional arrays
Initializing
Accessing Two-Dimensional Array Elements
Change Value of Array elements
Passing Arrays as Function Arguments
- Parameters as a pointer
- parameters as a sized array
- parameters as an unsized array
Return array from function
Return a pointer to an array by specifying the array's name without an index.
Example
02. C Pointers
Pointers (pointer variables) are used to store addresses rather than values.
Address in C
&
gives the address of the variable in memory
You will probably get a different address when you run the above code.
Declaration
A pointer points to either no address or a random address. where as, A variable has an address but contains random garbage value.
Assigning addresses to Pointers
int* pc, c;
c = 5;
pc = &c;
Get Value of stored in Pointers
*
is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.
Changing Value Pointed by Pointers
or
Pointer arithmetic
- Incrementing a Pointer
- Decrementing a Pointer
Pointer to array
Pointer to a function
Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. Unlike normal pointers, we do not allocate de-allocate memory using function pointers. A function’s name can also be used to get functions’ address.
Pointer to Pointer
Pointer contains the address of another pointer
NULL Pointers
A pointer that is assigned NULL is called a null pointer.
Void Pointer
The void pointer in C is a pointer which is not associated with any data types
-
Pointer arithmetic is not possible with void pointer due to its concrete size.
-
It can’t be used as dereferenced.
Near pointer
Used to store 16 bit addresses.
The limitation is that we can only access 64kb of data at a time.
Far pointer
Used to store 32 bit addresses.
Dangling Pointers
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.
- De-allocation of memory
- Variable goes out of scope
Advantage of pointer
-
Pointer reduces the code and improves the performance
-
We can return multiple values from a function using the pointer.
-
It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many applications of pointers in c language.
-
Dynamic memory allocation using malloc() and calloc() functions.
-
Arrays, Functions, and Structures
Dynamic memory allocation
The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime.
4 functions of stdlib.h header file.
- malloc()
- calloc()
- realloc()
- free()
malloc() function
The malloc() function allocates single block of requested memory.
Initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
calloc() function
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
Deference between malloc()
and calloc()
Initialization: malloc() - doesn't clear and initialize the allocated memory. calloc() - initializes the allocated memory by zero.
Speed: malloc() is fast. calloc() is slower than malloc().
Arguments & Syntax: malloc() takes 1 argument
- The number of bytes to be allocated
calloc() takes 2 arguments:
-
length the number of blocks of memory to be allocated
-
bytes the number of bytes to be allocated at each block of memory
Meaning on name: The name malloc means "memory allocation". The name calloc means "contiguous allocation".
03. Conditional statements
Conditionals with if, else
Decisions are based on conditions
Is raining
-> take raincoat
Computer programs also make decisions, using Boolean expressions (true/false) inside conditionals (if/else).
Example
Syntax
The condition is a Boolean expression: an expression that evaluates to either true or false.
How if statement works?
The if
statement evaluates the test expression inside the parenthesis ().
-
If the expression is evaluated to true,
- statements inside the body of if are executed.
- statements inside the body of else are skipped from execution.
-
If the expression is evaluated to false,
- statements inside the body of if are not executed.
- statements inside the body of else are executed
- Also called as branching
- Also called as control statements (controls the flow of execution of a program.)
Comparison operators
| operator | Greater | True Expressions |
| -------- | --------------------- | ---------------- |
| >
| Greater than | 60 > 32 |
| >=
| Greater than or equal | 60 >= 32 |
| <
| Less than | 20 < 32 |
| <=
| Less than or equal | 20 <=
32 |
| ===
| Strict equality | 32 === 32 |
| ==
| Equality | 32 == 32 |
| !==
| Strict inequality | 30 !== 32 |
| !=
| Inequality | 30 != 32 |
The else statement
To execute a different set of instructions when the condition is false, then we can use an else statement.
Example
Nested conditionals
When a program selects one of many paths, it can use nested or chained conditionals.
Pay attention to the syntax and formatting of your nested conditionals.
Chained conditionals (The if-else Ladder)
To check possible values of a single variable.
Compound Booleans with logical operators
To make shorter and more expressive code by combining simple Boolean expressions using logical operators (and, or, not) to create compound Boolean expressions.
The OR operator
either of two conditions are true.
or
DRY: Don't Repeat Yourself
The AND operator
both of the conditions are true
The NOT operator
Reverse the value of the expression
Example:
Referrals
https://www.khanacademy.org/computing/ap-computer-science-principles/programming-101/boolean-logic/a/conditionals-with-if-else-and-booleans
04. Errors
Core Dump (Segmentation fault) in C
Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you."
- When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump.
- It is an error indicating memory corruption.
- Modifying a string literal :
- Accessing an address that is freed :
-
Accessing out of array index bounds
-
Improper use of scanf()
05. Functions
A function is a block of code that performs a specific task.
A function is a set of statements that take inputs, do some specific computation and produces output.
Uses of functions
- To improve readability
- Reusability
- Easy to Debug
- Reduce the size of the code
Parameter and Arguments
Parameter: Is a variable in the declaration and definition of the function.
Arguments: Is the actual value of the parameter that gets passed to the function.
Function prototype or Declaration
Declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.
Syntax
returnType functionName(type1 argument1, type2 argument2, ...);
return_type: Return type can be of any data type such as int, double, char, void, short etc.
function_name: A name that convies the purpose of function.
argument list: Input variables names along with their data types.
Block of code: Statements which will be executed whenever a call will be made to the function.
Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax
functionName(argument1, argument2, ...);
Passing arguments to a function
Pass by value:
values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations.
Pass by reference:
Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.
Function definition
Function definition contains the block of code to perform a specific task.
Return Statement
Syntax
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
return (expression);
}
Types of functions
- Standard library functions
- User defined functions
Classification of function based on return values and arguments
- Function with arguments and with return value
- Function with arguments and without return value
- Function without arguments and without return value
- Function without arguments and with return value
Standard library functions
The standard library functions are built-in functions in C programming.
-
printf()
is a standard library function to send formatted output to the screen. The function is defined instdio.h
header file -
The
sqrt()
function calculates the square root of a number. The function is defined in themath.h
header file.
Advantages of using library functions
- They work
- Optimized for performance
- Saves development time
- Portable
- Provides abstraction
User-defined function
User created functions
How functions work in C
Every C program has a function called main() that is called by operating system when a user runs the program.
In C, functions can return any type except arrays and functions.
A function can call itself and it is known as “Recursion“.
Example:
06. Looping
World is full of repetition
Loops are used to repeat a set of instructions a specific number of times.
While Loop
A while loop is a way to repeat code until some condition is false It is a entry controlled or pre checking loop
Example
If condition inside the parenthesis never become false it will lead to Infinite Loops
Example for infinite loops are
while(true)
orfor(;;)
Do While loop
Condition is executed after the body of the loop. Also called as exist controlled loop.
Syntax:
Example:
Example :
For Loop
For loop starts with a 3 part header inside the parenthesis It is a entry controlled or pre checking loop
- Initialization of the for loop is performed only once
- Condition check is done on every start of every iteration. If the test expression is evaluated to false, the for loop is terminated.
- Incrementation/ Decrementation happens at the end of each iteration
Example:
Various forms of for loop in C
- Initialization part can be skipped from the loop
Note: Even though we can skip initialization part but semicolon (;) before condition is must, without which you will get compilation error.
- You can also skip the increment. Semicolon (;) is must after condition logic.
- The counter variable is initialized before the loop and incremented inside the loop.
for(;;)
is valid infinite loop
Nested Loops
Allows us to repeat along two dimensions
Break Statement
Used to exist the loop
Continue statement
Skip to next iteration without existing out of the loop
Example
07. Strings and Character array
String is a sequence of characters terminated by null character '\0'
Memory allocation
- String is not a data type in C
- A string is one-dimensional array of characters
Declaring string variables
Initializing a string variables
There are different ways to initialize a character array variable.
Assigning Values to Strings
The strcpy() function can be used to copy the string instead.
String Input and Output
Input function scanf() and gets() can be used with %s format specifier to read a string input from the terminal.
scanf()
terminates its input on the first white space it encounters.
String Handling Functions
C supports a large number of string handling functions in the standard library "string.h"
| Method | Description | | -------- | -------------------------------- | | strcat() | concatenate(combine) two strings | | strlen() | returns length of a string | | strrev() | reverse of a string | | strcpy() | Copies one string into another | | strcmp() | compare two string |
Passing strings to functions
08. Structure and Unions
Define structures
A struct (or structure) is a collection of variables (can be of different types) under a single name.
Syntax of struct
Example
Create struct variables
Creating struct variables allocates the memory
Another way is
Access members of a structure
.
- Member operator->
- Structure pointer operator
Example
Keyword typedef
typedef
keyword is used to create an alias name for data types.
is equivalent to
Nested Structures
Structures within a structure