You are on page 1of 62

Vallurupalli Nageswara Rao Vignana Jyothi Institute of

Engineering &Technology

Department of ECE

SUBJECT: C PROGRAMMING
Subject Code:

Topic Name: Introduction to C


I year, sec:

G Vijaya Kumar
Assistant Professor
Email: vijayakumar_g@vnrvjiet.in

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 1


Agenda
• Basic algorithms: Searching & Sorting
• Searching
• Linear search
• Binary Search)
• Basic sorting algorithms
• Bubble sort
• insertion sort
• selection
• Preprocessor Directives

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 2


Introduction to searching and sorting
• Searching is the process of finding the element in an Array

• Searching is successful if the element is found and unsuccessful if not found

• There two ways we can search array elements

1. Linear search

it is best to use when elements are random

2. Binary search

it is best to use when elements are arranged in order (ascending, descending etc..)

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 3


Linear Search
➢Linear search, also called as sequential search

➢it is a very simple method used for searching an array for a particular value.

➢It works by comparing the value to be searched with every element of the
array one by one in a sequence until a match is found.

➢Linear search is mostly used to search an unordered list of elements (array in


which data elements are not sorted).

➢Complexity of Linear search is O(n) where n is the number of elements in the


array

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 4


Linear Search: Algorithm
Linear Search:
BEGIN

Step1: Start from the leftmost element of Array

Step2: compare key with each element of Array one by one.

Step 3: If key matches with an element, return the index.

Step 4: If k doesn’t match any element until end, then return -1.

END

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 5


Flowchart
Flowchart:
A flowchart can also be defined as a
diagrammatic representation of an
algorithm

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 6


Pseudo code : Linear Search
BEGIN

READ INPUT ARRAY

FOR index FROM 0 -> length(Array):

IF Array[index] == search key THEN

Result=index

ENDIF

ENDLOOP

IF Result==-1 ? Not present : Print result

END
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 7
Program : Linear Search
#include <stdio.h> for (i = 0; i < n; i++)
void main() if (Data[i] == key)
{ result = i;
int Data[5], key,i,result=-1,n; (result == -1) ? printf(">>>Element is
//int Data[] = { 2, 6, 4,8,1}; not present in array<<<")
printf("Enter elements into array\n"); : printf("Element is present at
for(i = 0; i < 5; i++) index %d", result);
{
scanf("%d",&Data[i]); }
}
n = sizeof(Data) / sizeof(Data[0]);
printf("Enter element to be searched ?\n");
scanf("%d",&key);

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 8


Binary Search
➢ Binary search is a searching algorithm that works efficiently with a
sorted list
➢ Linear search is applicable for small data but if size increase
complexity also increases.
➢ For applying binary search, the array must be in sorted order
Algorithm: Binary search
Input: Array[1…N], key element
Output: if k is present successful, print the index else print
unsuccessful

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 9


Binary Search : Algorithm
BEGIN
1. initialize lower and upper bounds
2. status of searching initially false
3. repeat while until flag is true
4. find mid value
5. compare key with mid value
6. print “successful if found”
7. make flag value true
8. End if
9. if key less than a[mid]
10. make u=mid-1
11. else l=mid+1
12. end repeat
13. if flag=false
14. Print unsuccessful
STOP

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 10


Binary Search: pseudocode
BEGIN Else
L=1,U=N; Flag=false; L=mid+1;
While( flag!=true)&&(l<u) Do End if
Mid=(l+u)/2; End while
If(k=a[mid]) If (flag==false)

Then print “successful , index” Then


Then print “Un successful, not found”
Flag =true;
End if
End if
STOP
If(k<a[mid])
U=mid-1;

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 11


Binary Search: Program
#include <stdio.h> for(i=0;i<n;i++)

#define size 10 {
scanf("%d", &arr[i]);
void main()
}
{
printf("\n\n Enter search key\n");
int arr[size],key, i, n, l, u, mid, found=0;
scanf("%d", &key);
printf("\n Enter no of elements ");
l = 0, u = n-1;
scanf("%d", &n);
printf("\n Enter the elements: in
ascending order only\n");

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 12


Binary Search: Program
while(l<=u) else if (arr[mid]>key)

{ u = mid-1;
else
mid = (l + u)/2;
l = mid+1;
if (arr[mid] == key)
}
{
if (l > u && found == 0)
printf("\n %d is present at %d index",
printf("\n %d does not exist in the
key, mid); array",key);
found =1; }
break;
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 13


Sorting
➢ Sorting : it is a process of arranging the elements of array in some
order.
• Order may be either ascending or descending, numerical order, lexicographical order, or any
user-defined order.

➢ Example: int A[] = {21, 34, 11, 9, 1, 0, 22};


Then the sorted array (ascending order) can be given as:
A[] = {0, 1, 9, 11, 21, 22, 34};

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 14


Sorting
➢ There are three basic sorting algorithms
1. Bubble sort

2. Insertion sort

3. Selection sort

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 15


Bubble Sorting
➢Bubble sort is a very simple method that sorts the array elements

➢Sorts by repeatedly moving the largest element to the highest index position of the array(in case of
ascending order)

➢In bubble sorting, consecutive adjacent pairs of elements in the array are compared with each other.

➢If the element at the lower index is greater than the element at the higher index

➢then both elements are interchanged so that they maintain order

➢This process will continue till the list of unsorted elements exhausts

➢This procedure of sorting is called bubble sorting because elements ‘bubble’ to the top of the list

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 16


Understanding passes
➢Note that at the end of the first pass, the largest element in the list
will be placed at its proper position i.e, it moved to the highest index
of the array

➢If the elements are to be sorted in descending order, then in first pass
the smallest element is moved to the highest index of the array.

Example:
A[ ] ={3,2,1,4};

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 17


Understanding passes
A[ ] ={3,2,1,4};
Pass 1:
i) compare 3 & 2 3>2 Swap a[0],a[1]

A[ ] ={2,3,1,4}

ii) compare 3 & 1 3>1 Swap a[1],a[2]

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 18


Understanding passes

A[ ] ={2,1,3,4}

iii) compare 3 & 4 3<4 NO Swapping

Note: Here end of array is reached, and highest element


is placed at its proper position

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 19


Pass 2
A[ ] ={2,1,3,4}
Pass 2:

i) compare 2 & 1 2>1 Swap a[0],a[1]

A[ ] ={1,2,3,4}

ii) compare 2 & 3 2<3 No Swapping

Note: Here end of array is reached, and next highest element is placed at
its proper position

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 20


Pass 3
A[ ] ={1,2,3,4}

Pass 3:
ii) compare 1 & 2 1<2 No Swapping

A[ ] ={1,2,3,4}

Note: finally, array is sorted in n-1 passes

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 21


• The “bubble” sort is called so because, the list elements with
greater value than their surrounding elements “bubble” towards
the end of the list.

• For example, after first pass, the largest element is bubbled


towards the right most position.

• After second pass, the second largest element is bubbled


towards the second last position in the list and so on.

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 22


Bubble sort-example

Pass-1

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 23


Pass-2

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 24


Pass-3

Pass-4

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 25


Bubble sort complexity
Pass 1:
A[1] is compared with A[2]………………A[N-1] with A[n]
➢Total n-1 comparisons
Pass 2:
as last element is placed in its proper position, we need N-2
comparisons
….
Pass N-1: Array is sorted

So total passes required are N-1


Complexity is (N-1) +(N-2)+…(N-(N-1))= (N(N-1))/2
So, the complexity is O(n2)

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 26


Space Complexity of Bubble sort

• The space complexity for the algorithm is O(1), because only a


single additional memory space is required i.e. for temporary
variable used for swapping.

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 27


Bubble sort: Program
#include <stdio.h>
void main(){
int i,j,n,temp, arr[10];
printf("\n Enter no of elements \n");
scanf("%d", &n);
printf("Enter the Array elements: \n ");
for(i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 28


Bubble sort: Program
for(i=0;i<n-1;i++){ printf("\n sorted Array is :\n");

for(j=0;j<n-i-1;j++) for(i=0;i<n;i++)
printf("%d\t", arr[i]);
{
}
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 29


Selection Sorting
➢Selection sort is a simple sorting algorithm
➢sorted array is built one element at a time.
➢has a quadratic running time complexity of O(n2)
Steps:
➢ First find the smallest value in the array and place it in the first position
➢ Then, find the second smallest value in the array and place it in the
second position
➢ Repeat this procedure until the entire array is sorted
➢ Pass 1 : swap ARR[0] and smallest value in the array
➢ Pass 2 : swap smallest value in sub-array of N–1 element with ARR[1]
➢ Pass N–1: ARR[0], ARR[1], ..., ARR[N–1] is sorted

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 30


Selection Sorting
➢ Initial array
40 10 70 30 20

➢ Pass1: Find Smallest element in the array


40 10 70 30 20

➢ Swap with A[0]


10 40 70 30 20

➢ Pass2: find next smallest element in the array


10 40 70 30 20

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 31


Selection Sorting
➢ Pass2: find next smallest element in the array
10 40 70 30 20

➢ Swap with A[1]


10 20 70 30 40

➢ Pass3: find next smallest element in the array


10 20 70 30 40

➢ Swap with A[2]


10 20 30 70 40

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 32


Selection Sorting

➢ Pass4: find next smallest element in the array


10 20 30 70 40

➢ Swap with A[3]


10 20 30 40 70

➢ Finally, array is in sorted order

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 33


Selection sort: Program
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int arr[10], i, n,k=0,pos,temp,small;
printf("\n Enter no of elements\n");
scanf("%d", &n);
printf("Enter elements of array: \n ");
for(i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 34


Selection sort: Program
for(k=0;k<n;k++) printf("\n The sorted array is: \n");
{
for(i=0;i<n;i++)
pos = k;
small=arr[k]; printf(" %d\t", arr[i]);
for(i=k+1;i<n;i++){ }
if(arr[i]< small)
{
small = arr[i];
pos = i;
}
}
temp = arr[k];
arr[k] = arr[pos];
arr[pos] = temp;
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 35


Insertion Sorting
➢Insertion sort is a very simple sorting algorithm
➢sorted array is built one element at a time.
Example: ordering a deck of cards
➢inserts each item into its proper place
Steps:
➢The array of values to be sorted is divided into two sets
i. “Sorted”
ii. “unsorted”
➢ The sorting algorithm will proceed until there are elements in the
unsorted set
➢ Initially, the element at index 0 is in the sorted set.
➢ Rest of the elements are in the unsorted set
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 36
Insertion Sorting

➢Insertion sort is a very simple sorting algorithm


➢ The first element of the unsorted set has array index 1
➢ During each iteration of the algorithm, the first element in the
unsorted set is picked up and inserted into the correct position in
the sorted set.
➢ Initial array 40 10 70 30 20

40 10 70 30 20
➢ Divide into two lists
sorted list Unsorted list

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 37


Insertion Sorting
➢ Inserted first element into sorted list

10 40 70 30 20

sorted list Unsorted list

➢ Inserted next element


10 40 70 30 20

sorted list Unsorted list

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 38


Insertion Sorting
➢ Inserted next element

10 30 40 70 20

sorted list Unsorted list

➢ Inserted last element


10 20 30 40 70

sorted list Unsorted list is empty

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 39


Insertion sort: Program
#include <stdio.h> for(i=0;i<n;i++)

#include <conio.h> {
scanf("%d", &arr[i]);
#define size 5
}
void main(){
for(i=1;i<n;i++)
int arr[size], i,j,temp, n;
{
printf("\n Enter no of elements ");
temp = arr[i];
scanf("%d", &n); j = i-1;
printf("\n Enter the elements of the
array: ");

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 40


Insertion sort: Program
while((temp < arr[j]) && (j>=0)){
arr[j+1] = arr[j];
j--; }
arr[j+1] = temp;
}
printf("\n The sorted array is: \n");
for(i=0;i<n;i++)
printf(" %d\t", arr[i]);
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 41


Preprocessor Directives
• Preprocessors are programs that process our source code before compilation. There are a number of steps involved
between writing a program and executing a program in C .

• preprocessors directives tell the compiler to preprocess the source code before compiling. All of these preprocessor
directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates that, whatever statement starts with #, is going to
the preprocessor program, and preprocessor program will execute this statement

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 42


The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.

The preprocessor directives are broadly classified under three categories:

1) File inclusion directives/commands

2) Macro substitution directives/commands

3) Conditional compilation commands

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 43


File inclusion directives/commands
• This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files which can be included by the user in the program:

(i) Header File or Standard files: These files contains definition of pre-defined functions
like printf(), scanf() etc. Syntax: #include <filename>

where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the
compiler to look for the file in standard directory.

(ii) user defined files: When a program becomes very large, it is good practice to divide it
into smaller files and include whenever needed. These types of files are user defined files.
Syntax: #include “filename”
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 44
The # inlcude<filename> makes the preprocessor to include header files from the
system library.
The # inlcude"filename" makes the preprocessor to include files from the user-
defined directory.
#include <stdio.h>
contents of hello.c
#include <conio.h>
int display();
#include "hello.c“
int display()
main ( )
{
{
printf(“ welcome to vnrvjiet");
clrscr();
return 0;
printf (“hai”);
}
display();
}
Output
hai welcome to vnrvjiet
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 45
Macro substitution directives/commands
• Macro substitution is a process where an identifier in a program is replaced by a predefined string. The
preprocessor accomplishes this task under the direction of #define statement.
• Syntax for defining a macro # define identifier string
• If this statement is included in the program at the beginning, then the preprocessor replaces every
occurrence of the identifier in the source code by the string. The string may be any text, while the identifier
must be a valid C name.
• Note: There is no semi-colon(‘;’) at the end of macro definition. Macro definitions do not need a semi-
colon to end.
• There are different forms of macro substitution. The most common forms are :
• 1) Simple macro substitution
• 2) Argumented macro substitution
• 3) Nested macro substitution

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 46


Simple macro substitution
• Simple string replacement is commonly used to define constants.
• Ex: #define M 5
• will replace occurrences of M with 5, starting from the line of definition to the end
of the program. Consider the following two lines:
• total = M * value;
• printf(“ M= %d \n “, M);
• these two lines would be changed during preprocessing as follows:
• total = 5 * value;
• printf(“M = %d \n”, 5);
• A macro definition can include expressions also. Following are valid definitions
• # define AREA 5 * 12.46
• # define SIZE sizeof(int) * 4
• # define TWO-PI 2.0 * 3.1415926

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 47


Arugmented macro substitution
• The preprocessor permits us to define more complex and more useful form of replacements. It
takes the following form:

• #define identifier(f1,f2,f3-------fn) string

• Note that there is no space between the identifier and the left parentheses. The identifiers
f1,f2,f3,---fn are the formal macro arguments that analogous to the formal arguments in a
function definition.

• Subsequent occurrence of a macro with arguments is known as a macro call(similar to a


function call) . When a macro is called, the preprocessor substitutes the string, replacing the

formal parameters with actual parameters.

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 48


Augmented macro substitution
#include <stdio.h>
• A simple example of a macro with argument is
// macro with parameter
• #define CUBE(x) (x*x*x)
#define AREA(l, b) (l * b)
• If the following statement appears later in the program int main()
• Volume = CUBE(side); {
int l1 = 10, l2 = 5, area;
• Then the preprocessor would expand this statement to:
• Volume = ( side * side * side); area = AREA(l1, l2);

printf("Area of rectangle is: %d", area);

return 0;
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 49


Nested macro substitution
• We can also use one macro in the definition of another macro. That is, macro definitions may be nested. For
instance, consider the following macro definitions.
• #define M 5
• #define N M+1
• #define SQUARE(X) ( (x) * (x) )
• #define CUBE(X) (SQUARE(X) * (X))
• #define SIXTH(X) (CUBE(X) * CUBE(X))
• The preprocessor expands each #define macro, until no more macros appear in the text.
• For example, the last definition is first expanded into
• ((SQUARE(X) * (X)) * (SQUARE(X) * (X)))
• Since SQUARE(X) is still a macro, it is further expanded into ( ( ( (X) * (X) ) * (X) ) * ( ( (X) * (X) ) * (X) ) )
• Which is finally evaluated as x6.
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 50
Undefining macros:
Once defined, macro command can’t be redefined. Any attempt to redefine leads to the
compilation error. So to redefine a macro, so we must undefine it by using #undefine
command and define it again.

• Ex:

• #define SIZE 10

• --------------

• #undefine SIZE

• #define SIZE 20

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 51


Predefined Macros
• The macros which are predefined in C library are called as predefined macros

Command Meaning
__DATE__ Provides String “mm dd yyyy” format
__FILE__ Provides String constant containing name of source file
including path
__LINE__ Provides integer constant, containing current statement

__TIME__ Provides a string “hh:mm:ss” format


__STDC__ Provides a integer constant with value 1 if the compiler
confirms with ISO implementation.
February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 52
Conditional Compilation commands
C pre processor offers a feature known as conditional compilation, which can be used to switch ON (include) (or)

OFF (exclude)a particular line (or) group of lines in a program. There are 6 types:

1. Two-way command

2. Multi-way commands

3. Line commands

4. Error commands

5. Null commands

6. Pragma commands.

• Eg: #if, #else, #endif, #line, #error, #, #pragma etc.

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 53


Two-way command
• Syntax:
• #if expression
• Code to be included if expression is true
• #else
• Code to be included if expression is false
• #endif

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 54


Multi-way command:
• Syntax:

• #if expression1

• Code to be included if expression1 is true

• #elif expression2

• Code to be included if expression2 is true

• #else

• Code to be included if both expressions are false

• #endif

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 55


Line Command

• Syntax:1:- # line linenumber

• It command set the next line of the program to linenumber +1

• Syntax:2:- # line linenumber filename

• Set the next line of the program to linenumber+1 and create a program
name that is checked by predefined macrocall –FILE—

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 56


Error command
• Syntax: #if !defined (identifier)
• #error < error message>
• #endif
• Example:
#include <stdio.h>
#include<conio.h>
#define B 10
void main()
{
#if !defined(A)
# error macro A is not defined
#else
# printf(“ micro found”);
#endif
}

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 57


• “#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are included in source file.

• Otherwise, “else” clause statements are included in source file for compilation and execution.

• #include <stdio.h>

• #define RAJU 100

• int main()

• {

• #ifdef RAJU

• printf("RAJU is defined. So, this line will be added in " \

• "this C file\n");

• #else

• printf("RAJU is not defined\n");

• #endif

• return 0;

• }

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 58


Null command

i) C allows null command

• Syntax: #
• This is considered as null command and does not generate a compilation error.

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 59


Pragma command

• Syntax: #pragma tokens

• It makes the compiler to perform implementation defined action. It is used in the


advanced environments

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 60


References
• Programming in ANSI C, E. Balaguruswamy, Tata McGraw-Hill

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 61


THANK YOU

February 10, 2022 Department of ECE, VNRVJIET, Hyderabad 62

You might also like