C PROGRAMING LANGUAGE NOTES
Introduction to c language:
C programming is a general-purpose, procedural, structural computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. C is the most widely used computer language.
Procedural: A procedural language is a type of computer programming language that specifies
a series of well-structured steps and procedures within its programming context to compose a
program. It contains a systematic order of statements, functions and commands to complete a
program.
Structured programing language : A structured programming language is the
language that supports three patterns: sequence (an ordered list of statements),
selection (e.g. if statements) and repetition (e.g. loops).
-Typed programming language: A strongly-typed programming language is one in which each
type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is
predefined as part of the programming language and all constants or variables defined for a
given program must be described with one of the data types.
Why learn c language:
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Usage of c language:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Basic structure of a c program:
Basically a c program consists on six sections which are given bellow
1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions
1 .Documentation section: It includes the information specified at the
beginning of a program, such as a program's name, date, description, and title. It is
represented as:
//name of a program
[Link] section: The preprocessor section contains all the header files
used in a program. It informs the system to link the header files to the system
libraries. It is given by:
#include<stdio.h>
#include<conio.h>
[Link] section: this section define the all the symbolic constants
which are used in program by using define keyword. Given bellow
#define a = 2
[Link] declaration: The global section comprises of all the global declarations
in the program. It is given by:
float num = 2.54;
int a = 5;
char ch ='z';
We can also declare user defined functions in the global variable section.
[Link] function: main() is the first function to be executed by the
computer. It is necessary for a code to include the main(). It is like any other
function available in the C library. Parenthesis () are used for passing
parameters (if any) to a function.
The main function is declared as:
main()
[Link] defined functions: Subprogram section: If the program is a multi-function
program then the subprogram section contains all the user-defined functions that are
called in the main () function. User-defined functions are generally placed immediately
after the main () function, although they may appear in any order.
Escap sequence: An escape sequence is a sequence of characters that does not
represent itself when used inside a character examples are given bellow.
Comments in C language
Comments in C language are used to provide information about lines of
code. It is widely used for documenting code. There are 2 types of comments
in the C language.
1 .Single Line Comments 2. Multi-Line Comments
Single line comments are represented by double slash \\. Let's see an
example of a single line comment in C.
#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}
Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy
many lines of code, but it can't be nested. Syntax:
/*
code
to be commented
*/
Data types in c language : A data type specifies the type of data
that a variable can store such as integer, floating, character, etc.
Types data types are given bellow.
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types Memory Size Range
char 1 byte −128 to 127
signed char 1 byte −128 to 127
unsigned char 1 byte 0 to 255
short 2 byte −32,768 to 32,767
signed short 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 65,535
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte
signd 8 byte
long double 10 byte
Signed and unsigned data taypes:
In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using
them:
signed - allows for storage of both positive and negative numbers
unsigned - allows for storage of only positive numbers
For example,
// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int
// invalid code: unsigned int cannot hold negative integers
unsigned int num = -35;
Here, the variables x and num can hold only zero and positive values because we have used
the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas
variable x can hold values from 0 to 232-1.
Operators in c language: An operator is a symbol that operates on a value or a
variable. For example: + is an operator to perform addition.
Operatos in on basis of operand:
Operators in c on the basis of operations:
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
The precedence and associativity of C operators is
given below:
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision making in c language:
In a programing language the programmer’s uses decision making for one or more
conditions to be evaluated by the program the decision making always returns the
Boolean results true or false
There are various types of decision makings in c language which are given bellow
o If statement
o If-else statement
o If else-if ladder
o Nested if
If statement: The if statement is used to check some given condition and
perform some operations depending upon the correctness of that condition. It is
mostly used in the scenario where we need to perform the different operations for
the different conditions. The syntax of the if statement is given below.
if( expresion )
Code to be executed//
Follow chart of if statement :
If-else statement: The if-else statement is used to perform two operations for a
single condition. The if-else statement is an extension to the if statement using
which, we can perform two different operations, i.e., one is for the correctness of
that condition, and the other is for the incorrectness of the condition. Here, we must
notice that if and else block cannot be executed simultaneously. Using if-else
statement is always preferable since it always invokes an otherwise case with every
if condition. The syntax of the if-else statement is given below.
if (expiration ){
Code to be executed//
else{
Code to be executed//
Follow chart of if else :
If else-if ladder: The if-else-if ladder statement is an extension to the if-else
statement. It is used in the scenario where there are multiple cases to be performed
for different conditions. In if-else-if ladder statement, if a condition is true then the
statements defined in the if block will be executed, otherwise if some other
condition is true then the statements defined in the else-if block will be executed, at
the last if none of the condition is true then the statements defined in the else block
will be executed. There are multiple else-if blocks possible. It is similar to the switch
case statement where the default is executed instead of else block if none of the
cases is matched.
syntax
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Nested if: It is always legal in C programming to nest if-else statements, which
means you can use one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}
Nested If in C Programming is placing If Statement inside another IF Statement. Nested If in C is
helpful if you want to check the condition inside a condtion. If Else Statement prints different
statements based on the expression result (TRUE, FALSE). Sometimes we have to check even
further when the condition is TRUE. In these situations, we can use these C Nested IF
statements, but be careful while using it.
For example, every person is eligible to work if he is 18 years old or
above else he is not eligible. However, companies will not give a job to
every person. So, we use another IF Statement, also called as Nested If
Statement in C, to check his education qualifications or any specific
company requirements.
Syntax of nested if else statement :
f (Condition1)
{
if(Condition2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
if(Condition3)
{
Statement3;
}
else
{
Statement4;
}
}
Switch case statement: The switch statement allows us to execute one code
block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is
much easier to read and write.
Rolls for switch case statement :
Switch expiration must be an int or char
Case value must be an integer int char
Case must be inside switch
Break statement is not must
Flow chart of switch case statement:
Some important keywords:
1) Break: This keyword is used to stop the execution inside a switch block. It helps to
terminate the switch block and break out of it.
2) Default: This keyword is used to specify the set of statements to execute if there is
no case match.
Loops in c language:
Loops in programming come into use when we need to repeatedly execute a block of
code stamens, In computer programming, a loop is a sequence of instructions that is
repeated until a certain condition is reached.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested before
entering the loop body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at
the end of loop body. Therefore, the loop body will execute atleast once, irrespective of
whether the test condition is true or false. do – while loop is exit controlled loop.
For loop:
A for loop is a repetition control structure which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.
Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: int i=1;
Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i <= 10;
Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: i++;
Follow chart of for loop and syntax:
for (initialization expr; test expr; update expr)
// body of the loop
// statements we want to execute
}
While loop: While studying for loop we have seen that the number of iterations is known
beforehand, i.e. the number of times the loop body is needed to be executed is known to us.
while loops are used in situations where we do not know the exact number of iterations of loop
beforehand. The loop execution is terminated on the basis of test condition.
Follow chart of while loop and syntax:
initialization expression;
while (test_expression)
// statements
update_expression;
Do while loop: In do while loops also the loop execution is terminated on the basis of test
condition. The main difference between do while loop and while loop is in do while loop the
condition is tested at the end of loop body, i.e do while loop is exit controlled whereas the
other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
Flow chart and syntex: initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Infinite Loop: An infinite loop (sometimes called an endless loop ) is a piece of coding that
lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition
always evaluates to true. Usually, this is an error.
Nesting of loops : C supports nesting of loops in C. Nesting of loops is the feature in C
that allows the looping of statements inside another loop. Let's observe an example of nesting
loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining
any number of loops. The nesting level can be defined at n times. You can define any type of
loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
Syntax of Nested loo
Outer_loop
Inner_loop
{
// inner loop statements.
// outer loop statements.
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while'
loop.
C break statement:
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:
With switch case
With loop
C continue statement: continue statement is opposite to that of break statement,
instead of terminating the loop, it forces to execute the next iteration of the loop.
As the name suggest the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and next iteration of the loop will begin.
Functions in c language: In c, we can divide a large program into the
basic building blocks known as function. The function contains the set of
programming statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the C program.
Advantages of functions in c:
o By using functions, we can avoid rewriting same logic/code again and
again in a program.
o We can call C functions any number of times in a program and from
any place in a program.
o We can track a large C program easily when it is divided into multiple
functions.
o Reusability is the main achievement of C functions.
Functions aspects:
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c
program to tell the compiler about the function name, function
parameters, and return type.
o Function call Function can be called from anywhere in the program.
The parameter list must not differ in function calling and function
declaration. We must pass the same number of functions as it is
declared in the function declaration.
o Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes
when the function is called. Here, we must notice that only one value
can be returned from the function.
Types of Functions:
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C
header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
o Different aspects of function calling: function without arguments
and without return value
o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value
function without arguments and without return value:
#include<stdio.h>
void sum();
void main()
printf("\nGoing to calculate the sum of two numbers:");
sum();
void sum()
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
function without arguments and with return value:
#include<stdio.h>
int sum();
void main()
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
int sum()
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
function with arguments and without return value:
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
void sum(int a, int b)
printf("\nThe sum is %d",a+b);
function with arguments and with return value:
#include<stdio.h>
int sum(int, int);
void main()
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
int sum(int a, int b)
{
return a+b;
Call by value and Call by reference in C:
Call by value in C:
o In call by value method, the value of the actual parameters is copied
into the formal parameters. In other words, we can say that the value
of the variable is used in the function call in the call by value method.
o In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
o In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
o The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the
function definition.
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C:
o In call by reference, the address of the variable is passed into the function
call as the actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters, and
the modified value gets stored at the same address.
Consider the following example for the call by reference.
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Difference between call by value and call by reference in c:
No Call by value Call by reference
.
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to the Changes made inside the function validate outside of
function only. The values of the actual parameters do the function also. The values of the actual parameters
not change by changing the formal parameters. do change by changing the formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the same
different memory location memory location
C Recursion: A function that calls itself is known as a recursive function. And, this technique is
known as recursion. The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call, and other doesn't.
Advantages and Disadvantages of Recursion:
Recursion makes program elegant. However, if performance is vital, use loops instead as recursion is
usually much slower.
That being said, recursion is an important concept. It is frequently used in data structure and algorithms.
For example, it is common to use recursion in problems such as tree traversal.
Pointers in c: The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer
By the help of * (indirection operator), we can print the value of pointer variable.
int *a;//pointer to int
char *c;//pointer to char
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and
calloc() functions where the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It
reduces the code and improves the performance.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
Types of pointer:
Null pointer
Void pointer
Dangling pointer
Wild pointer
Null pointer:
A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the
segment. The null pointer basically stores the Null value while void is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null means that
the pointer is referring to the 0th memory location.
If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer.
When a NULL value is assigned to the pointer, then it is considered as a Null pointer.
Double pointer:
A pointer is used to store the address of variables. So, when we define a pointer to pointer, the
first pointer is used to store the address of the second pointer. Thus it is known as double
pointers.
Void pointer:
Till now, we have studied that the address assigned to a pointer should be of the same type as specified
in the pointer declaration. For example, if we declare the int pointer, then this int pointer cannot point
to the float variable or some other type of variable, i.e., it can point to only int type variable. To
overcome this problem, we use a pointer to void. A pointer to void means a generic pointer that can
point to any data type. We can assign the address of any data type to the void pointer, and a void
pointer can be assigned to any type of the pointer without performing any explicit typecasting.
Wild pointer:
Pointers store the memory addresses. Wild pointers are different from pointers i.e. they also store the
memory addresses but point the unallocated memory or data value which has been deallocated. Such
pointers are known as wild pointers.
A pointer behaves like a wild pointer when it is declared but not initialized. That is why, they point any
random memory location.
Here is an example of wild pointers in C++ language,
Dangling pointer:
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated
from memory without modifying the value of the pointer. In this case, the pointer is pointing to the
memory, which is de-allocated. The dangling pointer can point to the memory, which contains either the
program code or the code of the operating system. If we assign the value to this pointer, then it
overwrites the value of the program code or operating system instructions; in such cases, the program
will show the undesirable result or may even crash. If the memory is re-allocated to some other process,
then we dereference the dangling pointer will cause the segmentation faults.
Avoiding Dangling Pointer Errors:
The dangling pointer errors can be avoided by initializing the pointer to the NULL value. If we assign
the NULL value to the pointer, then the pointer will not point to the de-allocated memory.
Assigning NULL value to the pointer means that the pointer is not pointing to any memory location.
Arithmetic operations on pointers:
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we
know that pointer contains the address, the result of an arithmetic operation performed on the pointer
will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the
result will be an integer value. Following arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Illegal arithmetic with pointers:
There are various operations which can not be performed on pointers. Since, pointer stores address
hence we must ignore the operations which may lead to an illegal address, for example, addition, and
multiplication. A list of such operations is given below.
o Address + Address = illegal
o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal
o ~Address = illegal
Array in c:
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
Why we need to use array :
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of
a student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
Properties of Array:
The array contains the following properties.
Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array:
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array:
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList
Two Dimensional Array in C:
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. However, 2D arrays are created to
implement a relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.