c & data structure
c & data structure
Computer is an advanced electronic device that takes raw data as an input from the user and processes
it under the control of a set of instructions (called program), produces a result (output), and saves it for
future use
Functionalities :
CPU (Central Processing Unit): CPU is considered as the brain of the computer. CPU performs all
types of data processing operations. It stores data, intermediate results, and instructions
(program). It controls the operation of all parts of the computer. CPU itself has the following
three components –
ALU (Arithmetic Logic Unit) ---All types of processing, such as comparisons, decision-making
and processing of non-numeric information takes place here and once again data is moved to
RAM.
Memory Unit ---This is unit in which data and instructions given to computer as well as results
given by computer are stored. Unit of memory is "Byte". 1 Byte = 8 Bits
Control Unit---- CPU extracts instructions, performs execution, maintains and directs
operations of entire system.
Functions of Control Unit Control unit performs following functions –
It controls all activities of computer Supervises flow of data within CPU Directs flow of data
within CPU Transfers data to Arithmetic and Logic Unit Transfers results to memory Fetches
results from memory to output devices
In a C program, single-line comments can be written using two forward slashes i.e., //,
and we can create multiline comments using /* */.
Global Declaration This section includes all global variables, function declarations, and
static variables. The variables declared in this section can be used anywhere in the
program. They're accessible to all the functions of the program. Hence, they are called
global variables
Main() Function In the structure of a C program, this section contains the main function
of the code. The compiler starts execution from the main() function. It can use global
variables, static variables, inbuilt functions, and user-defined functions. The return type
of the main() function can be void and also not necessarily int.
Elements of C Programming Language
Character Set in C Language Type Set
Lowercase a-z
Uppercase A-Z
Digits 0-9
special characters !,@,#,$,%
White space space, tab, and new lines
Keywords: 1) they are those elements of C language whose meaning has already being
defined or explained. 2) keyword are called pre-defined words. 32 keywords in C
language
Auto, Do, Goto, Break Void ,Else ,Int ,Case, Double ,Sizeof ,Enum ,Long,If, While,,For ,
Const, Volatile, Float, Return ,Union, Const,
signed, unsigned, static, struct ,char ,extern ,register, continue, default, typeodef, short
Variables: It is the most fundamental aspect of any language. It is a location in the
Computer memory which can store value and is a given symbolic name for easy
reference. Variable declaration requires that you inform c of the variable's name and
date data types. Example: int page_no; char grade; float salary;
int page-no=10; char grade='A'; float salary= 1200.50; int a=10, b=20, c=30;
Expressions: An expression consist of combination of operands, operators, variables and
functions calls. An expression can be arithmetic, logical, or relational. Example of
Expressions: a+b=c [arithmetic operation] a>b [relational operation] a==b [logical
operations] func(a,b) [function calls]
Statement: A statement is a complete instruction to the computer. In C, statements are
indicated by semicolon ; at the end. Example: legs =4; it is a statement. legs=4 it is an
expression.
What is algorithm?
An algorithm is a procedure or step-by-step instruction for solving a problem. They form
the foundation of writing a program.
Step 1: Start Step
2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
Step 5: Display sum
Step 6: Stop
For writing any programs, the following has to be known: Input Tasks to be
preformed Output expected
Flowchart: Flowchart is a diagrammatic representation of sequence of logical steps of a
program. Flowcharts use simple geometric shapes to depict processes and arrows to
show relationships and process/data flow.
Start/Stop
Process
Input/output Onpage
connector use
numbers
decision
Integer Types:
The integer data type in C is used to store the whole numbers without decimal values.
Octal values, hexadecimal values, and decimal values can be stored in int data type in C
Size: 2 bytes or 4 bytes Format Specifier: %d
Character Types Character data type allows its variable to store only a single character.
Size: 1 byte Format Specifier: %c
Floating-Point Types In C programming float data type is used to store floating-point
values. Float in C is used to store decimal and exponential values. It is used to store
decimal numbers (numbers with floating point values) with single precision.
Size: 4 bytes Format Specifier: %f
Arithmetic Operators: An arithmetic operator performs mathhematical operations such
as addition, subtraction, multiplication, division etc on numerical values (constants and
variables).
+ addition or unary plus - subtraction or unary minus * Multiplication / division %
remainder after division (modulo division)
Example 1: Arithmetic Operator
// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output
a+b=13 a-b = 5 a*b = 36 a/b = 2
Increment and Decrement Operators: C programming has two operators increment ++
and decrement -- to change the value of an operand (constant or variable) by 1.
Assignment Operators: An assignment operator is used for assigning a value to a
variable. The most common assignment operator is =
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Relational Operators : Equal to
Greater than
Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Logical Operators An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming
Logical AND, Logical OR, Logical NOT
Control Structures :: control the flow of execution in a program.
1. Decision making/Conditional/Branching/sectional Statements
1. Simple if 2. if-else 3. if-else-if ladder 4. nested if 5. Switch
1. simple if:
2. The syntax :
3. If (condition1) {
4. Body of if statement;
5. }
6. Next statement;
7. Program:
8. include <stdio.h>
9. int main ()
10.{
11.int a = 10;
12.if( a < 20 )
13.{
14.printf("a is less than 20\n" );
15.}
16.printf("value of a is : %d\n", a);
17.return 0;
18.}
19.e If… Else Statement:
20.If (condition 1) { Statement 1 ; } else { Statement 2 ; } Next Statement;
21.Program: #include<stdio.h>
22.void main()
23.{ i
24.nt num1, num2;
25.printf("Please Enter Two different values\n"); s
26.canf("%d %d", &num1, &num2);
27.if(num1 > num2) { printf("%d is Largest\n", num1);
28.}
29.else { printf("%d is Largest\n", num2);
30.}
31.}
32. Switch Statements:
33.Switch (expression_A) { case_A: Statement 1; break; case_B: Statement 2 ; break; case_C;
Statement 3 ; break; …. case_Z: Statement N; break; Default: Default Statement; break; } Next
statement;
34.
35.
2. Looping Statements/Iterative Statements
WHILE LOOP- Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10; /
* while loop execution */
while( a < 20 )
{ printf("value of a: %d\n", a);
a++;
}
return 0;
}
FOR LOOP- Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
#include <stdio.h>
int main ()
int a;
for( a = 10;
a < 20;
a=a+1)
return 0;
DO—WHILE”” It is more like a while statement, except that it tests the condition at the
end of the loop body.
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
Do
{
printf("value of a: %d\n", a);
a = a + 1;
}
while( a < 20 );
return 0;
}
NESTED LOOPS You can use one or more loops inside any other while, for, or do..while
loop.
3. Jump Statements/Loop control statements
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 labeled statement.
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */ break;
}
}
return 0;
Output: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of
a: 15
continue statement:
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.
Array::
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.
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.
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 which
we will learn later.
Types of Arrays:
Arrays can be classified into types:
1.One dimensional array 2
The one-dimensional array can be defined as a sequential collection of elements. The 1D array is
also called as linear array.
Declaration of C Array We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
The simplest way to initialize an array is by using the index of each element.
80 60 70 85 75
Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]
int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
for(i=0;i<5,i++)
{
Printf(“%d\n “,marks[n]);
}
return 0;
}
Declaration with Initialization We can initialize the c array at the time of declaration. Let's see
the code. 1. int marks[5]={20,30,40,50,60}; In such case, there is no requirement to define the
size. So it may also be written as the following code. 1. int marks[]={20,30,40,50,60}; Let's see
the C program to declare and initialize the array in C
Two Dimensional Array: 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.
e. It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required
data_type array_name[rows][columns];
int twodimen[4][3];
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
arr[0][0] = 1
4 is the number of rows, and 3 is the number of columns arr[0][1] = 2
Two-dimensional array example in C arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
#include<stdio.h> arr[1][2] = 4
int main() arr[2][0] = 3
{ arr[2][1] = 4
arr[2][2] = 5
int i=0,j=0;
arr[3][0] = 4
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[3][1] = 5
for(i=0;i<4;i++) arr[3][2] =
{
For(j=0;j<3;j++;)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
Return 0;
}
Functions:
In c, we can divide a large program into the basic building blocks known as function.
A function can be called multiple times to provide reusability and modularity to the C program
The function is also known as procedure or subroutine in other programming languages.
Advantage :: we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program
Reusability is the main achievement of C functions
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.
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.
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.
Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
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
In c there are two methods to pass the data into the function in c language, i.e.,
printf("Before function call x=%d \n", x); Before adding value inside function num=100
change(x);//passing value in function After adding value inside function num=200
printf("After function call x=%d \n", x); After function call x=100
return 0;
}
Call by Value Example: Swapping the values of the two variables
#include <stdio.h> Before swapping the values in main a =
void swap(int , int); //prototype of the function 10, b = 20
int main() After swapping values in function a = 20,
{ b = 10
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.
#include <stdio.h>
int main()
{
int x=100;
return 0;
}
CALL BY REFERENCE EXAMPLE: SWAPPING THE VALUES OF THE TWO VARIABLES
#include <stdio.h>
void swap(int *, int *); //prototype of the function Before swapping the values in main
int main() a = 10, b = 20
{
After swapping values in function a
= 20, b = 10
int a = 10;
After swapping values in main a =
int b = 20; 20, b = 10
{
int temp;
temp = *a;
*a=*b;
#include<stdio.h>
int main()
{
int n,f;
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
nter the number whose factorial you
{ want to calculate?5 factorial = 120
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
POINTERS: 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
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
malloc() allocates single block of requested memory.-- It returns NULL if memory is not sufficient
calloc() allocates multiple block of requested memory- It initially initialize all bytes to zero. It
returns NULL if memory is not sufficient
realloc() reallocates the memory occupied by malloc() or calloc() functions.- If memory is not
sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it
changes the memory size
free() frees the dynamically allocated memory- The memory occupied by malloc() or calloc()
functions must be released by calling free() function. Otherwise, it will consume memory until
program exit.
Pointer Expressions
Structures Arrays allow to define type of variables that can hold several data items of the same kind.
Union A union is a user defined data type available in C that allows to store different data types in
the same memory location.
To define a union, you must use the union statement in the same way as you did while defining a
structure
C Strings The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
Difference between char array and string literal: There are two main differences between char array
and literal. o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array
gets() function: The gets() function enables the user to enter some characters followed by the enter
key. All the characters entered by the user get stored in a character array. The null character is
added to the array to make it a string. The gets() allows the user to enter the space-separated
strings.
puts() function: The puts() function is very much similar to printf() function. The puts() function is
used to print the string on the console which is previously read by using gets() or scanf() function
String Functions;;
1) strlen(string_name) returns the length of string name.
3) strcat(first_string, second_string) concats or joins first string with second string. The result of
the string is stored in first string.
4) strcmp(first_string, second_string) compares the first string with second string. If both strings are
same, it returns 0.
DATA STRUCTURES?
Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organising data in the computer so that it can be
used efficiently.
Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Data Structures are widely used in almost every aspect of Computer Science i.e.
Operating System, Compiler Design, Artifical intelligence, Graphics and many
more.
Linear Data Structures:: A data structure is called linear if all of its elements are
arranged in the linear order. In linear data structures, the elements are stored in
non-hierarchical way where each element has the successors and predecessors
except the first and last element.
Arrays: An array is a collection of similar type of data items and each data item
is called an element of the array. The data type of the element may be any valid
data type like char, int, float or double
Stack:: A Stack is a linear data structure that follows the LIFO (Last-In-First-Out)
principle.
Stack has one end, whereas the Queue has two ends (front and rear). It contains
only one pointer top pointer pointing to the topmost element of the stack.
Whenever an element is added in the stack, it is added on the top of the stack,
and the element can be deleted only from the stack.
In other words, a stack can be defined as a container in which insertion and
deletion can be done from the one end known as the top of the stack.
The following are some common operations implemented on the stack:
push(): When we insert an element in a stack then the operation is known as a push. If the stack
is full then the overflow condition occurs. - we initialize a stack, we set the value of top as -1
or NULL to check that the stack is empty. top=top+1, and the element will be placed at the new
position of the top
pop(): When we delete an element from the stack, the operation is known as a pop. If the stack
is empty means that no element exists in the stack, this state is known as an underflow state. -
> top=top-1.
isEmpty(): It determines whether the stack is empty or not.
isFull(): It determines whether the stack is full or not.'
peek(): It returns the element at the given position.
count(): It returns the total number of elements available in a stack.
change(): It changes the element at the given position.
display(): It prints all the elements available in the stack.
ABC*DE^F^/G*-H*+
Sorting Algorithms::
1.Selection Sort – ( complexity in all cases o(n2))
2. selects the smallest (or largest) element from the unsorted portion
of the list and swaps it with the first element of the unsorted part.
3. arr[] = {64, 25, 12, 22, 11}
4. index 0,1,2,3,4
1.3,0,5,6
2.0,3,5,6
Third pass :: 1.check the final sorted list
1.12,11,13,5,6
8.5,11,12,6,13
9.5,11,6,12,13
Merge Sort
Complexity in all cases o(n log n)
divide the array into two halves, sort each half, and then merge the sorted
halves back together.
O(n)
Quick Sort Ω(n log(n)) θ(n log(n)) O(n2))