web viewbell teacher: a new student approached the zen master and asked how he should prepare...

81
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur- 03. Module-3: Arrays, Strings and Functions Introduction to Arrays: Normally, the programmer makes the use of scalar variable to store and process single value. However, it is necessary for the programmer to store and process large volume of data in computer’s memory while developing the programs to solve complex problems and is possible by making the use of data structure or derived data type named array. The examples to store and process large volume of data in computers memory by using an array are as follow. i. To store and process roll numbers of 100 students int rno[100]; ii. To store and process total marks of 100 students int marks[100]; iii. To store and process name of a candidate char name[25]; iv. To store and process names of 100 candidates char name[100][25]; Definition of an array: “An array can defined as a collection of related data elements of the same data type stored in computer’s memory to store and process large volume of data” Or “An array can defined as a fixed size sequenced collection of data elements of similar data type stored in consecutive computer’s memory” Examples: Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 1

Upload: phungdung

Post on 06-Feb-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Module-3: Arrays, Strings and Functions

Introduction to Arrays:

Normally, the programmer makes the use of scalar variable to store and process

single value. However, it is necessary for the programmer to store and process large volume

of data in computer’s memory while developing the programs to solve complex problems

and is possible by making the use of data structure or derived data type named array.

The examples to store and process large volume of data in computers memory by

using an array are as follow.i. To store and process roll numbers of 100 students int rno[100];

ii. To store and process total marks of 100 students int marks[100];

iii. To store and process name of a candidate char name[25];

iv. To store and process names of 100 candidates char name[100][25];

Definition of an array:

“An array can defined as a collection of related data elements of the same data type

stored in computer’s memory to store and process large volume of data”

Or

“An array can defined as a fixed size sequenced collection of data elements of similar

data type stored in consecutive computer’s memory”

Examples:

1. To define an array with the name ‘a’ of type int i.e. to store and process maximum number

of 100 integer values instead of defining 100 separate variables.

int a[100];Index/

subscript0 1 2 3 4 99

a

The machine allocates 100 memories continuously with the common name ‘a’. The

individual memories can be identified by common array name with the index values i.e.

starts with 0 and end with ARRAY SIZE-1.

The integer values can be stored in array elements with common array name ‘a’ with

different index values as follow.a[0]= 15, a[1]=25,a[2]=35, a[3]=45,a[5]=55,…….,a[99]=125;

Index 0 1 2 3 4 99

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 1

Page 2: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

a 15 25 35 45 55 125

The total memory allocated by this array is 200 bytes (100 memories x 2 bytes=200

bytes).

2. To define an array with the name avg of float type to store and process percentage of

marks of 100 students instead of defining 100 separate variables.

float avg[100];Index 0 1 2 3 4 99avg

The floating point values can be stored in array elements with common array name

‘avg’ with different index values as follow.avg[0]= 90.59, avg[1]=80.89,avg[2]=70.88, avg[3]=93.67,avg[5]=87.55,…….,avg[99]=69.25;

Index 0 1 2 3 4 99a 90.59 80.89 70.88 93.67 87.55 69.25

The total memory allocated by this array is 400 bytes (100 memories x 4 bytes=400

bytes).

3. To store and process name of a student in character array or string variable.

char name[25]; /* character array or string variable*/

strcpy(name,”John”);Index 0 1 2 3 4 24name J o h n \0

The total memory allocated by this array is 25 bytes (25 memories x 1 byte=25 bytes).

4. To store two strings (words)

char str1[50], str2[50];

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 2

Page 3: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Types of arrays:

The arrays can be classified according to the volume of data to be stored in computer’s

memory.

1. One dimensional array e.g. int a[100];

2. Two dimensional array e.g. int a[100][100];

3. Multi dimensional array e.g. int a[100][100][100];

1. One dimensional array:

“One dimensional array can defined as a collection of related data elements of the

same data type stored in consecutive computer’s memory to store and process linear list of

data elements”

The individual arrays elements can be processed by using common array name with

different index that starts with 0 and ends with the ARRAY SIZE–1.

Declaration of one-dimensional array:

The one dimensional array must be declared in the declaration part of the main()

before the array elements are used in the executable part of main() by using following

syntax.

Syntax:

data_type array_name[ARRAY_SIZE];

where,

data_type the data type of data to be stored and processed in computer’s memory like int,

float, char, double, long int, etc.

array_name valid identifier

ARRAY_SIZE the integer constant indicating maximum number of data elements can be

stored.

Examples:

int a[5]; Index 0 1 2 3 4a

float price[5]; Index 0 1 2 3 4price

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 3

Page 4: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

double result[5]; Index 0 1 2 3 4result

char name[5]; Index 0 1 2 3 4name

char city[5]; Index 0 1 2 3 4city

Note: Computer allocates 5 memory locations with garbage (unknown) values

Initialization of one dimensional array:

The process of assigning the values to the defined array elements is called

initialization of array. The arrays can be initialized with the values in the following two

ways.

1. Compile Time Array Initialization

2. Run Time Array Initialization

1. Compile Time Array Initialization: If the values are well known by programmers well

in advance, then the programmer makes the use of compile time initialization. The process of

assigning the values during the declaration of arrays in the declaration part of main() is

called compile time initialization. The syntax is as follow.

Syntax:

data_type array_name[ARRAY_SIZE]={Value1,Value 2,………….,Value n};

where,

data_type the data type of data to be stored and processed in computer’s memory like int,

float, char, double, long int, etc.

array_name valid identifier

ARRAY_SIZE the integer constant indicating maximum number of data elements can be

stored.

Examples:

1. int a[5]={10,20,30,40,50};

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 4

Page 5: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

or

a[0]=10, a[1]=20, a[2]=30, a[3]=40, a[4]=50; Index 0 1 2 3 4

A 10 20 30 40 50

2. float price[5]={55.50,99.50,100.50,75.60,50.60};Index 0 1 2 3 4price 55.50 99.50 100.50 75.60 50.60

3. char name[5]=”John”; or char name[5]={‘J’,’o’,’h’,’n’};

or char name[ ]=”John”Index 0 1 2 3 4Name J O H n ‘\0’

char name[5]={‘J’};Index 0 1 2 3 4Name J ‘\0’ ‘\0’ ‘\0’ ‘\0’

4. int a[5]={0,0,0,0,0}; or int a[5]={0};Index 0 1 2 3 4

a 0 0 0 0 05. int a[5]={10, 20};

Index 0 1 2 3 4a 10 20 0 0 0

6. int a[3]={1,2,3,4,5}; /* invalid i.e. to many initialization*/

2. Run Time Array Initialization: If the values are not known by programmers in advance

then the programmer makes the use of run time initialization. It helps the programmers to

read unknown values from the end users of a program by the keyboard by using input

functions like scanf() getch() and gets(),etc.

Examples:

Partial Initialization of Array: If the number of values to be initialized is less than the size

of the array then it is called as partial initialization. The remaining locations will be

initialized to zero automatically

Ex: Consider the array shown below

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 5

Page 6: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

int p[5]={10,20};

Even though we have declared 5 as a array-size but we have initialized only 2 elements in

the array. So other locations are initialized to 0 automatically by compiler as shown below.

Index 0 1 2 3 4

10 20 0 0 0

p[0] p[1] p[2] p[3] p[5]

Here, elements of index 2,3 and 4 are initialized to 0 automatically by compiler

Array Initialization without Size: Consider the example shown below

int b[ ]={10,15,20,25,30}; Size is not specified

In this initialization even though we have not specified the size of array ‘b’, but array

elements are initialized with 5 different values. The array size will be set to total number of

values specified in the array. The compiler will calculate the size of array based on the

number of initial values. Since number of elements is 5 so totally 5*2bytes = 10 bytes are

reserved where 2 is size of integer.

Accessing the element of array:

Consider an array consist of 7 integer element

int p[7]={15,9,8,19,29,36,85};

We can access the elements of array using index or subscript of element. Index gives the

position of the elements in the array.

Index 0 1 2 3 4 5 6

15 9 8 19 29 36 85

p[0] p[1] p[2] p[3] p[4] p[5] p[6]

p[0]=15, p[1]=9, p[2]=8, p[3]=19, p[4]=29, p[5]=36, p[6]=85

Index of first element of array is 0.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 6

Page 7: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

1. To read and display 5 integer values from a keyboard by using an array.

#include<stdio.h>#include<conio.h>void main(){int a[5],i;clrscr();printf("\n Enter any 5 integer values");for(i=0;i<5;i++){scanf("%d",&a[i]);}for(i=0;i<5;i++){printf("\n%d",a[i]);}getch();}

2. To read and display ‘n’ integer values from a keyboard by using an array.

#include<stdio.h>

#include<conio.h>void main(){int a[50],i,n;clrscr();printf("\n Enter n: ");scanf("%d",&n);printf("\n Enter %d integer values: ",n);for(i=0;i<n;i++){scanf("%d",&a[i]);}printf("\n Array Elements ");for(i=0;i<n;i++){printf("\n%d",a[i]);}getch();}

Assignment Questions:

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 7

o/p:Enter any 5 integer values10 20 30 40 50

o/p:Enter n: 7 Enter 7 integer values10 20 30 40 50 60 70Array Elements1020…70

a[0] a[1] a[2] a[3] a[4]10 20 30 40 50

Page 8: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

1. What is one dimensional array? Explain its declaration and initialization with syntax and examples. (2+2+2=6 marks) (Model QP)

2. What is two dimensional array? Explain its declaration and initialization with syntax and examples. (2+2+2=6 marks)3. Write a c program to implement bubble sort technique.4. Write a c program to find largest of ‘n’ numbers.5. Write a c program to read N integers into an array A and to

i. Find the sum of odd numbersii. Find the sum of even numbersiii. Find the average of all numbers

Output the results computed with appropriate headings. (06 marks June/July 2015)6. Write a program to multiple of two arrays of given order a[m x n] and b[ p x q] (09 marks Jan. 2015)

Anyone who stops learning is old, whether at twenty or eighty~ Henry Ford

“When Henry Ford decided to produce his famous V-8 motor, he chose to build an engine with the entire eight cylinders cast

in one block, and instructed his engineers to produce a design for the engine. The design was placed on paper, but the engineers

agreed, to a man, that it was simply impossible to cast an eight-cylinder engine-block in one piece.

Ford replied,''Produce it anyway.”~  Henry Ford

What we usually consider as impossible are simply engineering problems ~ Michio Kaku

***

Programming Examples on one dimensional arrays

/* To find largest and lowest of n numbers*/

#include<stdio.h>

#include<conio.h>

void main()

{

int a[5],i,n,max,min;

clrscr();

printf("\n Enter n: ");

scanf("%d",&n);

printf("\n Enter %d values: ",n);

for(i=0;i<n;i++)

{

scanf("%d",&a[i]);

}

max=min=a[0];

for(i=1;i<n;i++)

{

if (a[i]>max)

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 8

o/p:

Enter n: 5

Enter 5 values: 10 2 45 67 12

Largest number is 67

Lowest number is 2

Page 9: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

max=a[i];

if (a[i]<min)

min=a[i];

}

printf("\n Largest number is %d",max);

printf("\n Lowest number is %d",min);

getch();

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 9

Page 10: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* To find sum of odd,even,all and avg of N numbers by using array */

#include<stdio.h>

#include<conio.h>

void main()

{

int a[5],i,n,sum=0,esum=0,osum=0;

float avg;

clrscr();

printf("\n Enter n: ");

scanf("%d",&n);

printf("\n Enter %d values: ",n);

for(i=0;i<n;i++)

{

scanf("%d",&a[i]);

}

for(i=0;i<n;i++)

{

if (a[i]%2==0)

esum=sum+i;

else

osum=osum+i;

sum=sum+a[i];

}

avg=(float)sum/n;

printf("\n Sum of even numbers=%d",esum);

printf("\n Sum of odd numbers=%d",osum);

printf("\n Sum of all numbers=%d",sum);

printf("\n Average of all numbers=%f",avg);

getch();

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 10

o/p:

Enter n: 5

Enter 5 values: 1 2 3 4 5

Sum of even numbers = 9

Sum of even numbers = 6

Sum of all numbers = 15

Average of all numbers =3.000000

Page 11: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Sorting Techniques in CThe process of arranging the elements in the ascending order or descending order is the sorting. There are 2 sorting technique 1) Bubble Sort 2) Selection Sort

Bubble Sort: Bubble sort technique starts by comparing the first two elements of an array and swap the elements if necessary (Swapping is nothing but interchanging the elements), i.e., if you want to sort the elements of array in ascending order and if the first element is greater than second then, you need to swap the elements.

If the first element is smaller than second, you must not swap the element. Then, again second and third elements are compared and swapped if it is necessary and this process go on until last and second last element is compared and swapped. This completes the first step of bubble sort.

In the first level of sorting highest elements of the list will settles at bottom position.In the second level of sorting second highest element will settles at second bottom position and so on. Each and every level largest element settles at the bottom and smallest elements bubbles up.

The following figure illustrates the working of bubble sort

Bubble sort technique

Here, there are 5 elements to the sorted. So, there are 4 steps(levels).

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 11

Page 12: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Program to sort n numbers using Bubble sort technique */#include<stdio.h>#include<conio.h>void main(){int n, a[25], i, j, temp;clrscr();printf("Enter n:");

scanf("%d",&n);

printf("\n Enter any %d values",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\nBefore sorting\n");

for(i=0;i<n;i++)

printf("\t%d",a[i]);

for(i=0;i<n;i++)

{

for(j=0; j<n-i-1 ;j++)

{

if (a[j]> a[j+1])

{

temp=a[j];

a[j]=a[j+1];

a[j+1]= temp;

}

}

}

printf("\nAfter sorting\n");

for(i=0;i<n;i++)

printf("\t%d",a[i]);

getch();

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 12

o/p:Enter n: 5Enter any 5 values: 5 4 3 2 1Before Sorting5 4 3 2 1After Sorting1 2 3 4 5

Page 13: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Selection Sort: Selection sort algorithm starts by comparing first two elements of an array

and swap the elements if necessary, i.e., if you want to sort the elements of array in

ascending order and if the first element is greater than second then, you need to swap the

elements but, if the first element is smaller than second, leave the elements as it is.

Then, again first element and third element are compared and swapped if necessary. This

process goes on until first and last element of an array is compared. This completes the first

step of selection sort.

If there are n elements to be sorted then, the process mentioned above should be repeated 

n -1times to get required result.

Following figure shows the working of selection sort technique

Fig: Selection sort technique

In above example the first number 20 is compared with second number 12. Since first

number is larger than second number then swap the numbers. Then compare the second

number with third number if swapping is necessary then swap the number otherwise

compare third element with fourth element and so on up to n.

C Program for illustrating Selection sort technique

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 13

Page 14: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* C Program to sort the numbers in ascending order using selection sort technique*/

#include<stdio.h>

#include<conio.h>

void main( )

{

  int n,i,j,temp,a[20];

  printf("Enter total elements: ");

  scanf("%d",&n);

  printf("Enter %d elements: ",n);

  for(i=0;i<n;i++)

      scanf("%d",&a[i]);

  for(i=0;i<n;i++)

{

      for(j=i+1;j<n;j++)

{

           if(a[i]>a[j])

{

               temp=a[i]; /*Swapping technique*/

              a[i]=a[j];

              a[j]=temp;

           }

      }

  }

  printf("After sorting is: ");

  for(i=0;i<n;i++)

      printf(" %d",a[i]);

  getch( );

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 14

Output

Enter total elements:5

Enter 5 elements: 25 10 5 43 29

After Sorting is: 5 10 25 29 43

Page 15: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Program to find sum and average of N numbers using array */#include<stdio.h>#include<conio.h>void main(){int a[25],n,i,sum=0;float avg;clrscr();printf("Enter n:");

scanf("%d",&n);

printf("\nEnter any %d values",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

for(i=0;i<n;i++)

{

sum=sum+a[i];

}

avg=(float)sum/n;

printf("\n Sum of all numbers=%d",sum);

printf("\n Average of all numbers=%f",avg);

getch();

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 15

o/p:Enter n: 5Enter any 5 values: 1 2 3 4 5Sum of all numbers = 15Average of all numbers = 3.000000

Bell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained. "Give me a soft tap, and you will get a tiny ping. Strike hard, and you'll receive a loud, resounding peal."People's reactions to this story:"You get out of something what you put into it.""The more you try, the more a good teacher will help.""Be careful what you ask for. The universe may just provide you with what you seek.""Sounds like the master is saying pay me a lot, and I will help you a lot; pay me little, and that's what I'll give you in return.""I think the teacher was warning the student that if he is struck he will strike back with equalforce."

Page 16: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Searching Techniques in C Programming Language

More often we will be working on large amount of data. It may be necessary to determine

whether a particular item is present in that large amount of data. The Process of finding a

particular element in the large amount of data is called as Searching.

There are 2 types of searching techniques

1) Linear Search

2) Binary Search

1) Linear Search( Sequential Search): A linear search also called as Sequential Search

is a simple searching technique. In this technique we search for a given specific

element called as key element in the large list of data in sequential order( One after

another) from first element to last element. If the key element is present in the list of

data then search is Successful. Otherwise, search is Unsuccessful.

Ex: int a[5]={10,20,30,40,50};

Index 0 1 2 3 4

10 20 30 40 50

a[0] a[1] a[2] a[3] a[4]

Consider above example where array ‘a’ contains 5 integer elements.

If user wants to search a key element 30 from given list of elements, then search begins

from first element of array i.e. 10(Index is 0). Then it checks this element with given key

element. If both element are same then it is called as “SUCESSFUL SEARCH” and it

returns the position of that particular element in the array. If the element is not present in the

array then it is called as “UNSUCESSFUL SEARCH” and it returns -1. So here in above

example the search is successful and the key element is present at Position

3(Position=index+1).

Following is the C Program for Linear Search Technique

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 16

Page 17: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Program to implement linear search technique by using an array*/

#include<stdio.h>

#include<conio.h>

void main()

{

int a[25],n,i,key ;

clrscr();

printf("Enter n:");

scanf("%d",&n);

printf("\n Enter any %d values",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\n Enter item to be search:");

scanf("%d",&key);

for(i=0;i<n;i++)

{

if (key==a[i])

{

printf("\n Item found at %d position",i+1);

getch();

exit();

}

}

printf("\n Item not found!");

getch();

}Advantages:

1) Very simple approach.2) Works well for small arrays3) Used to search when the elements are not sorted.

Disadvantages:1) Less efficient if the array is large

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 17

o/p:Enter n: 5Enter any 5 values: 15 22 31 88 55Enter item to be search: 88Item found at 4 position

o/p:Enter n: 5Enter any 5 values: 15 22 31 88 55Enter item to be search: 100Item not found !

Page 18: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

2) If the elements are the already sorted, linear search is not efficient.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 18

Page 19: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Binary Search Technique: A binary search is simple and very efficient searching technique which can be applied if the items to be compared are either in ascending order or descending order.

The general idea behind Binary Search technique is finding middle element from the sorted list of element. If given Key element is less than middle element search towards left side of middle element, otherwise search towards right side. This process is repeated until key element is found or key element is not found.

If key element is found then return position of that element. If key element is not found then retuen -1.

Consider the array shown below

int a[10]={10,20,30,40,50,60,70,80,90,100};

index: 0 1 2 3 4 5 6 7 8 9

10 20 30 40 50 60 70 80 90 100

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

low high

low --> Represents the first element of array where index is 0. Hence low=0.High --> Represents the last element of array where last index is 9 i.e. n-1. Hence high=n-1.

low=0 high=n-1( n is total number of elements)

So position of middle element is obtained by

mid=(low+high)/2 Here in above example mid=(0+9)/2=4. Because the mid value is integer.

This suggest that the element which is at index 4 is the middle element. So middle element is 50.

Case 1) Now key element is compared with middle element. If both elements are same then return mid value.

if(key==a[mid]) return mid;

Case 2) If key element to be search is less than middle element then search towards left of the middle element. i.e.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 19

Page 20: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

if(key<a[mid])high=mid-1;

high=mid-1 searches towards left side of middle element Case 3) If Key element to be search is greater than middle element then search towards right side of middle element. i.e.

if(key>a[mid]) low=mid+1;

low=mid+1 searches towards right side of middle element.

Finally if key element to be searched is not present in the list, then it returns -1.

/* Program to implement binary search technique by using an array*/#include<stdio.h>#include<conio.h>void main(){int a[25], n, i, key, low, high, mid;float avg;clrscr();printf("Enter n:");scanf("%d",&n);printf("\n Enter any %d values in ascending order: ",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\n Enter item to be search:");

scanf("%d",&key);

low=0;

high=n-1;

while(low<=high)

{

mid=(low+high)/2;

if (key==a[mid])

{

printf("\n Item found at %d position",mid+1);

getch();

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 20

o/p:Enter n: 5Enter any 5 values in ascending order: 1 2 3 4 5Enter item to be search: 3Item found at 3 position

o/p:Enter n: 5Enter any 5 values in ascending order: 1 2 3 4 5Enter item to be search: 8Item not found !

Page 21: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

exit(0);

}

if (key>a[mid])

low=mid+1;

if (key<a[mid])

high=mid-1;

}

printf("\n Item not found!");

getch();

}

Advantage: Very efficient searching technique.

Disadvantage: Array elements should be in sorted.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 21

Page 22: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Two dimensional arrays:

A two dimensional array helps the programmers to store and process table of data

elements of similar type in computer’s primary memory RAM. It is similar to a matrix

containing numbers of rows and columns. The rows and columns of 2D array are indexed by

starting from 0(zero). i.e row index starts with 0 and end with ROW_SIZE-1 and column

index starts with 0 and end with COLUMN_SIZE-1.

The 2D arrays elements can be processed by using common array name with two

index representing row and column.

Examples:

1. To store and process 6 subject marks of 5 students.

int a[5][6];

Col-0 Col-1 Col-2 Col-3 Col-4 Col-5Row-0 65 75 90 80 66 68Row-1Row-2Row-3Row-4 50 60 70 80 90 99

In each row, programmer can store 6 subject marks of each student.

a[0][0]=65, a[0][1]=75, a[0][2]=90, a[0][3]=80, a[0][4]=66, a[0][5]=68;

….

a[4][0]=50, a[4][1]=60, a[4][2]=70, a[4][3]=80, a[4][4]=90, a[4][5]=99;

2. To store and process table of integer values containing 2 rows & 3 columns.

int a[2][3];

0 1 201

2. To store and process table of floating point numbers of the size 3 x 2.

float b[3][2];

0 1012

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 22

Page 23: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Declaration of two-dimensional array:

The two dimensional array must be declared in the declaration part of the main()

before the array elements are used in the executable part of main() by giving common name

with two indexes representing no. of rows and columns. The syntax is as follow.

Syntax:

data_type array_name[ROW_SIZE] [COLUMN_SIZE];

where,

data_type the data type of data to be stored and processed in computer’s memory like int,

float, char, double, long int, etc.

array_name valid identifier

ROW_SIZE & COLUMN_SIZE the maximum number of row and column elements can

be stored ( The values should be integer).

Examples:

1. To store the integer values for 5 x 5 matrix.

int a[5][5];Col-0 Col-1 Col-2 Col-3 Col-4

Row-0Row-1Row-2Row-3Row-4

Total memory occupied by this array is ( 5 x 5 x 2 bytes=50 bytes)

2. To store and process table of integer values containing 2 rows & 3 columns.

int a[2][3];0 1 2

01

3. To store the names of 100 students

char name[100][25];

Total memory occupied by this array is ( 100 x 25 x 1 byte=25000 bytes)

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 23

Page 24: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Initialization of two dimensional array:

The process of assigning the values to the defined array elements of 2D array is called

initialization of 2D array. The array elements can be initialized with different in the

following two ways.

1. Compile Time Array Initialization

2. Run Time Array Initialization

1. Compile Time Array Initialization: If the values are well known by programmers in

advance, then the programmer makes the use of compile time initialization. i.e the process of

assigning the values during the declaration of arrays in the declaration part of main() is

called compile time initialization. The syntax is as follow.

Syntax:

data_type array_name[ROW_SIZE] [COLUMN_SIZE]=

{

{list of values },

{list of values },

{list of values }

};

Examples:

int a[2][3]={ or int a[2][3]={10,20,30,40,50,60};

{10,20,30},

{40,50,60}

};

int a[3][2]={10,20,30,40,50,60};

int a[ ][2]={0,0,0,0};

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 24

0 1 20 10 20 301 40 50 60

0 10 10 201 30 402 50 60

0 10 0 01 0 0

Page 25: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

1. Run Time Array Initialization: If the values are not known by programmers in advance

then the programmer makes the use of run time initialization. i.e. programmer reads values

from users through the keyboard by using input functions like scanf() getch() and gets(),etc.

Examples:

1. To read and display integer values for m x n matrix by using 2D array./* To read and display values for (m x n) matrix*/#include<stdio.h>#include<conio.h>void main(){int a[25][25],m,n,i,j;clrscr();printf("Enter the order of matrix A:");scanf("%d%d",&m,&n);printf("\n Enter %d values in row order: ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&a[i][j]);}

}printf("\n Array Elements \n");for(i=0;i<m;i++){

for(j=0;j<n;j++){printf("\t%d",a[i][j]);}printf("\n");

}getch();}

Assignments:

1. Write a c program to find addition of two matrices A and B of the same size.

2. Write a c program to find multiplication two matrices A(m,n) and B(p,q).

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 25

o/p:

Enter the order of matrix A: 2 3

Enter 6 values in row order: 1 2 3 4 5 6

Array Elements

1 2 3

4 5 6

Page 26: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Addition of two matrices*/#include<stdio.h>#include<conio.h>void main(){int a[25][25],b[25][25],c[25][25],m,n,i,j;clrscr();printf("Enter the order of both the matrix A and B:");scanf("%d%d",&m,&n);printf("\nEnter %d values of A matrix: ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&a[i][j]);}

}printf("\nEnter %d values of B matrix: ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&b[i][j]);}

}/* code to find addition of matrix*/

for(i=0;i<m;i++){

for(j=0;j<n;j++){c[i][j]=a[i][j]+b[i][j];}

}

printf("\n Resultant Matrix \n");for(i=0;i<m;i++){

for(j=0;j<n;j++){printf("\t%d",c[i][j]);}printf("\n");

}getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 26

o/p:Enter the order of both matrix A & B : 2 3

Enter 6 values of A matrix : 1 2 3 4 5 6

Enter 6 values of B matrix : 1 2 3 4 5 6

Resultant Matrix

2 4 6

8 10 12

Page 27: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Substraction of two matrices*/#include<stdio.h>#include<conio.h>void main(){int a[25][25],b[25][25],c[25][25],m,n,i,j;clrscr();printf("Enter the order of both the matrix A and B:");scanf("%d%d",&m,&n);printf("\nEnter %d values of A matrix: ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&a[i][j]);}

}printf("\nEnter %d values of B matrix: ",m*n);for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&b[i][j]);}

}/* code to find substraction of matrix*/

for(i=0;i<m;i++){

for(j=0;j<n;j++){c[i][j]=a[i][j]-b[i][j];}

}

printf("\n Resultant Matrix \n");for(i=0;i<m;i++){

for(j=0;j<n;j++){printf("\t%d",c[i][j]);}printf("\n");

}getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 27

o/p:Enter the order of both matrix A & B : 2 3

Enter 6 values of A matrix : 1 2 3 4 5 6

Enter 6 values of B matrix : 1 1 2 2 3 3

Resultant Matrix

0 1 1

2 2 3

Page 28: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Multiplication of two matrices*/#include<stdio.h>#include<conio.h>void main(){int a[25][25],b[25][25],c[25][25],m,n,p,q,i,j,k;clrscr();printf("Enter the order of matrix A:");scanf("%d%d",&m,&n);printf("Enter the order of matrix B:");scanf("%d%d",&p,&q);if (n==p){printf("\n Multiplication of A and B is possible\n");printf("\nEnter values of A matrix: ");for(i=0;i<m;i++){

for(j=0;j<n;j++){scanf("%d",&a[i][j]);}

}printf("\nEnter values of B matrix: ");for(i=0;i<p;i++){

for(j=0;j<q;j++){scanf("%d",&b[i][j]);}

}/* code to find multiplication of matrix*/for(i=0;i<m;i++){

for(j=0;j<n;j++){c[i][j]=0;

for(k=0;k<n;k++)c[i][j]+=a[i][k]*b[k][j];

}}printf("\n Resultant Matrix \n");for(i=0;i<m;i++){

for(j=0;j<q;j++){printf("\t%d",c[i][j]);}printf("\n");

}}else

printf("\n Multiplication is not possible!");getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 28

o/p:Enter the order matrix A & B : 2 3Enter the order matrix A & B : 3 2 Multiplication is possibleEnter values of A matrix : 1 1 1 1 1 1Enter values of B matrix : 1 1 1 1 1 1Resultant Matrix 3 3 3

3 3 3

o/p:Enter the order matrix A & B : 2 3Enter the order matrix A & B : 2 3Multiplication is not possible

Page 29: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* C Program to print transpose of given matrix*/#include <stdio.h>#include<conio.h>void main(){ int a[10][10];

int i, j, m, n;  printf("Enter the order of the matrix \n"); scanf("%d %d", &m, &n); printf("Enter the coefiicients of the matrix\n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { scanf("%d", &a[i][j]); } } printf("The given matrix is \n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { printf(" %d", a[i][j]); } printf("\n"); } printf("Transpose of matrix is \n"); for (j = 0; j < n; ++j)

{ for (i = 0; i < m; ++i) { printf(" %d", a[i][j]); } printf("\n"); } getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 29

Output:Enter the order of the matrix3 3Enter the coefiicients of the matrix3 7 92 7 56 3 4The given matrix is 3 7 9 2 7 5 6 3 4Transpose of matrix is 3 2 6 7 7 3 9 5 4

Page 30: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* C Program to print principal diagonal elements of the matrix*/#include<stdio.h>#include<conio.h>void main(){int a[20][20],i,j,m,n;clrscr();printf("enter the rows and columns of the matrixs\n");scanf("%d%d",&m,&n);printf("Enter the first matrics\n");for(i=0;i<m;i++) {  for(j=0;j<n;j++)      {      scanf("%d",&a[i][j]);   //reads the matrics      } }printf("The diagonal element of the matrics are\n");for(i=0;i<m;i++) {  for(j=0;j<n;j++)      {      if(i==j)      printf("%d ,",a[i][j]);   //prints the diagonal element of the matrics      }

 } getch(); }

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 30

Page 31: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Introduction to Strings

The use of strings plays very important role, while developing the user friendly

software. Hence, it is necessary for the programmer to store and process strings within

computers memory. To read and display the strings, the programmer makes the use of I/O

functions like scanf(), printf(), gets() and puts(). C supports different string handling

functions like strcmp(), strcat(), strcpy() and strupr(),strlwr(), etc. to perform different

operations on strings to get desired results.

“A string constant or literal can be defined as a sequence of characters enclosed in

double quotes that will be treated as single data element”

Technically, a string constant is an array of characters. By default, each string ends

with the NULL character (\0) that helps the programmer to identify the end of string.

Examples:

1) “Brain W. Kernighan and Dennis M. Ritchie”

2) “Computer Programming in C”

3) “VTU”

4) “A”

5) “2015” and

6) “ ” etc.

Declaration and Initialization of string variables:

The character arrays are also called as string variables. The string variables must be

defined and initialized in same way of array declaration and initialization.

Syntax: char string_variable[size];

Example:

1) To store name of a student. char name[25];

strcpy(name,“Thomas”);

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 31

V T U \0

0 1 2 3 4 5 6 24Name T h o m a s \0 \0

Page 32: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

2) To store names of 3 students. char name[5][25];

strcpy(name[0],“Thomas”);strcpy(name[1],“Alice”);strcpy(name[2],“Bob”);

Reading and Writing Strings:

The strings can be read and write by using following I/O functions.

1. scanf() and printf()

2. gets() and puts()

The scanf( ) reads a string until white space found from a keyboard, whereas gets( )

reads a string until user press ENTER KEY.

The printf( ) helps to write (display) strings on the monitor screen in different formats

with appropriate message, whereas puts () helps to display only the string on monitor

screen without format./* To read and siplay strings by using scanf() and printf() */#include<stdio.h>void main(){char name[5][25];clrscr();printf("Enter your name: ");scanf("%s",name);printf("Hello! %s",name);getch();}

/* To read and siplay strings by using gets() and puts() */#include<stdio.h>void main(){char name[25];clrscr();printf("Enter your name");gets(name);printf("Hello! ");puts(name);getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 32

o/p:Enter your name: Alice BobHello ! Alice Bob

o/p:Enter your name: Alice BobHello ! Alice Bob

0 1 2 3 4 5 6 240 T h o m a s \

0\0

1 A l i c e \0 \02 B o b \

0\0

Page 33: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Program to find length of a string without using string built-in function*/#include<stdio.h>#include<conio.h>

void main(){char str[25];int i,count=0;clrscr();printf("Enter a string");gets(str);for(i=0;str[i]!='\0';i++){count++;}printf("\n Length of a string is %d",count);getch();}

/* Program to copy one string1 into string2 without using string built-in function*/#include<stdio.h>#include<conio.h>

void main(){char str1[25],str2[25];int i;clrscr();printf("Enter string1 to be copy: ");gets(str1);for(i=0;str1[i]!='\0';i++){str2[i]=str1[i];}str2[i]='\0';printf("\nString Copied\n");printf("\nString1=%s String2=%s",str1,str2);getch();}

/* To reverse a string without using string builtin function*/#include<stdio.h>#include<string.h>void main(){char str[25];int i,len,temp;clrscr();printf("Enter string to be reverse: ");gets(str);len=strlen(str)-1;for(i=0;i<strlen(str)/2;i++){temp=str[i];str[i]=str[len];str[len--]=temp;}printf("\n The reversed string is %s",str);getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 33

o/p:Enter a string: AliceLength of a string is 5

o/p:Enter string1 to be copy: AliceString CopiedString1= Alice String2=Alice

o/p:Enter string to be reverse: techThe reversed string is hcet

Page 34: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

String Manipulating Functions/ String Built-in Function:

C supports different string handling functions to perform different operations on

strings. All the string handling functions are stored in string.h file. Some of the most

common used string functions are as follow.

Sl.No. Function Description1 strlen() Returns number of characters in the given string2 strcpy() Copies the given source string to another destination string variable3 strncpy() Copies first n characters from source to destination4 strcmp() Compares two strings for their similarity5 strncmp() Compares first n characters from two strings for their similarity6 strcat() Concatenates (joins) two strings into single string 7 strncat() Concatenates first n characters from source string to destination8 strupr() Converts characters into uppercase9 strlwr() Converts characters into lowercase10 strrev() Reverses a given string

1. strlen(): It returns the number of characters in the given string.Syntax:

strlen(string);

Examples:

int len;len=strlen(“vtu”); len=3

int len;char str[]=”vtu”;len=strlen(str); len=3

Programming Example:

/* To find length of a string */#include<stdio.h>#include<string.h>void main(){char str[50];int len;clrscr();printf("Enter a string");gets(str);len=strlen(str);printf("\n Length of the string is %d",len);getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 34

o/p:Enter a string : vtuLength of the string is 3

Page 35: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

2. strcpy(): It copies the contents of source string to another destination string variable. Syntax: strcpy(destination, source string); Examples: char str1[25]=”vtu”,str2[25]; strcpy(str2,str1); printf(“copied string is %s”,str2);

o/p: Copied string is vtu

Programming Example:

/* To copy a string */#include<stdio.h>#include<string.h>void main(){char str1[50],str2[50];clrscr();printf("Enter string1 to be copy: ");gets(str1);strcpy(str2,str1);printf("\n Copied string is %s",str2);getch();}3. strncpy(): It copies the number of characters from source string to another destination string variable. Syntax: strcpy(destination, source string, n); where, n number of characters to be copy

Examples: char str1[25]=”Technology”,str2[25]; strcpy(str2,str1,4); printf(“copied string is %s”,str2); o/p: Copied string is Tech

4. strcmp(): It compares given two strings for their similarity character by character. If, the given strings are same then it returns zero; otherwise, non-zero (ASCII difference of dissimilar characters). Syntax: strcmp(string1,string2);

Examples: char str1[25]=”VTU”,str2[25]=”VTU”;

int temp; temp=strcmp(str1,str2);

temp=0 /* because both are same */

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 35

o/p:Enter string1 to be copy : vtuCopied string is vtu

Page 36: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

char str1[25]=”Ant”,str2[25]=”Cat”;int temp;

temp=strcmp(str1,str2); temp=-2 /* ASCII of ‘A’ – ASCII of ‘C’ i.e. 65-67=-2 */

5. strncmp(): It compares given two strings for their similarity for the specified number of characters from the beginning. If, the given strings are same then it returns zero; otherwise, non-zero (ASCII difference of dissimilar characters). Syntax:

strncmp(string1,string2,n);where, n number of characters to be compare.Examples:

char str1[25]=”THERE”,str2[25]=”THEIR”; int temp; temp=strncmp(str1,str2,3); temp=0 /* because first 3 characters are same */

6. strcat(): It concatenates (joins) two strings into a single string. Syntax: strcat(string1,string2); Example:

char str1[25]=”Honey”, str2[25]=”well”, str3[25]; strcpy(str3,strcat(str1,str2)); printf(“%s”,str3);

o/p: Honeywell

7. strncat(): It concatenates (joins) only specified number of characters from source to destination string. Syntax: strncat(string1,string2,n); where, n number of characters to be joined. Example:

char str1[25]=”Honey”, str2[25]=”well”, str3[25]; strcpy(str3,strcat(str1,str2,2)); printf(“%s”,str3);

o/p: Honeywe

8. strrev(): It reverses a string. Syntax: strrev(string);

Example: char str1[25]=”computer”;

strrev(str1); printf(“%s”,str1);

o/p: retupmoc

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 36

Page 37: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* check string for palindrome */#include<stdio.h>#include<string.h>void main(){char str1[25],str2[25];clrscr();printf("Enter a string:");gets(str1);strcpy(str2,str1);strrev(str1);if(strcmp(str1,str2)==0)printf("\n Palindrome");elseprintf("\n Not palindrome");getch();}

9. strupr(): It converts the characters of a given string into uppercase. Syntax: strupr(string); Example:

char str1[25]=”computer”; strupr(str1); printf(“%s”,str1);

o/p: COMPUTER

10. strlwr(): It converts the characters of a given string into lowercase. Syntax: strlwr(string); Example:

char str1[25]=”COMPUTER”; strlwr(str1); printf(“%s”,str1);

o/p: computer

***

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 37

o/p:Enter a string : madamPalindromeo/p:Enter a string : teacherNot Palindrome

Page 38: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Functions or SubprogramsIntroduction to Functions: As we know, every C program permits the programmer to make use only one main ( ) to solve a problem. Hence, it is very difficult for the programmer to solve a large and complex problem by using single main() with only built-in functions. Hence, programmers write different sub programs to do specific task. These subprograms written by programmers are called subprograms or user defined functions or modules. The programming approach in which the given large and complex problem will be divided into many subprograms and are called by main() to do specific task is called modular programming approach. “A function can be defined as a subprogram that contains a group of statements to do specific task”Examples:

A function to find sum of two numbers int sum (int x, int y){return(x+y); or}

int sum (int x, int y){int ans;ans=x+y;return (ans);}

A function to find area of circlefloat area (float x){return(3.142*x*x); or}

float area (float x){float ans;ans=3.142*x*x;return(ans);}

A function to find largest of two numbersint large (int x, int y){if (x>y) return x; orelse return y;}

int large (int x, int y){int ans; if (x>y) ans=x; else ans=y;return (ans);}

Advantages of writing user defined functions1. Reduction in the size of main( ).2. Reusability of the written functions.3. Program maintenance, testing and debugging is easier.4. Functions can be shared among many C files.5. Programmers can create their own functions library like header files.6. Modular programming approach.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 38

Page 39: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Elements of user defined functions:

In order to design and develop user defined functions of sub programs the programmer needs to establish and use the following three elements of user defined functions.

i. Function declaration or prototype

ii. Function call

iii. Function definition

The programming example that includes all the three elements is as follows.

/* to find sum of two numbers by using function*/#include<stdio.h>int sum(int x, int y); /* function prototype*/void main(){int n1,n2,ans;clrscr();printf("\n Enter any two numbers");scanf("%d%d",&n1,&n2);ans=sum(n1,n2); /* function call*/printf("\n Addition is %d",ans);getch();}int sum(int x, int y) /* function definition*/{return (x+y);}

(i) Function declaration or prototype: The function must be declared in the global declaration part of the C program i.e. before the main( ). It provide three details of function to be write to C-compiler. The syntax is as follows.Syntax: return_type function_name (arguments list);where,return_type The data type of return value like int,cfloat, char, double etc. The default return type is int.function name valid identifier.arguments list Number of inputs or parameters or arguments.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 39

o/p:Enter any two numbers: 7 3Addition is 10

Page 40: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Examples:

int sum (int x, int y); or int sum(int, int) /* to find sum*/

float area (float x); or float area (float) /* to find area of circle*/

void STRCOPY(char str1[],char str2[]); /* to copy str1 into str2*/

long int fact(long int x); /* to find factorial */

int isprime (int x); /* to check of prime number*/

Note: If you write the function before the main() then no need to declare the function.

ii. Function call: The user defined function is called by the main() function to do specific task by passing the number of actual parameters.

Examples:i) void main() { … ans1=square(n); /* function call*/ ans2=cube(n); /* function call*/ … }2) void main() { … r=isprime(i); /* function call*/ … }3) void main() { … rightrot(x,n); /* function call*/ … }

iv. Function definition: This is the subprogram, which can be written before or after the main(). To write function, the programmer needs to provide three details of function to C compiler. They are, return type, function name and number of parameters to be received.

Syntax:

return_type function_name (arguments list) {

local definitions; statements; return (value); }

Examples:1) To find addition of factorial of ‘n’ number.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 40

Page 41: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

int sum (int x, int y) { int ans; ans=x+y; return (ans); }2) To find factorial of ‘n’ number.

long int fact(int x){int i, prod=1; for(i=1;i<=x;i++) { prod=prod*I; } return (prod);}

3) To check for prime number.int isprime(int x){int i; for(i=2;i<=x/2;i++) { if (x%i==0) return 0; } return(1);}

Programming Examples on user defined functions or subprograms

/* to find square and cube of number by using functions*/

#include<stdio.h>int square(int); /* function declaration*/int cube(int);

void main(){int n,ans1,ans2;clrscr();printf("\n Enter a number");scanf("%d",&n);ans1=square(n); /* function call*/ans2=cube(n); /* function call*/printf("\n Square is %d",ans1);printf("\n Cube is %d",ans2);getch();}

int square(int x) /* function definition*/{return (x*x);}int cube(int x) /* function definition*/{return (x*x*x);}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 41

o/p:Enter a number: 2Square is 4Cube is 8

Page 42: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* to find factorial n by using function*/#include<stdio.h>

long int fact(long int x); /* function declaration*/

void main(){long int n,ans;clrscr();printf("\n Enter a number");scanf("%ld",&n);ans=fact(n); /* function call*/printf("\n Factorial is %ld",ans);getch();}

long int fact(long int x) /* function definition*/{long int prod=1;int i; for (i=1;i<=x;i++) { prod=prod*i; }return(prod);}

/* to check for prime number by using function*/#include<stdio.h>int isprime(int x); /* function declaration*/void main(){int n,r;clrscr();printf("\n Enter a number");scanf("%d",&n);r=isprime(n); /* function call*/if(r==1)printf("\n %d is prime number",n);elseprintf("\n %d is not prime number",n);getch();}

int isprime(int x) /* function definition*/{int i; for (i=2;i<=x/2;i++) { if(x%i==0) return 0; }return(1);}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 42

o/p:Enter a number: 1717 is prime number

o/p:Enter a number:2424 is not prime number

o/p:Enter a number: 4Factorial is 24

Page 43: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* to copy string1 into string2 by using user defined function*/#include<stdio.h>void STRCOPY(char str1[],char str2[]); /* function declaration*/void main(){char str1[50],str2[50];clrscr();printf("\n Enter string1 to be copy: ");gets(str1);STRCOPY(str1,str2); /* function call*/getch();}

void STRCOPY(char str1[],char str2[]) /* function definition*/{int i; for (i=0;str1[i]!='\0';i++) { str2[i]=str1[i]; } str2[i]='\0';printf("\n String copied...");printf("\n string1=%s string2=%s",str1,str2);}

Assignments

1. Explain string declaration and initialization with examples.

2. Write a c program to find length of a string without using string handling function.

3. Explain any FIVE string manipulating functions with syntax and examples.

4. What is user defined function? Give example.

5. List advantages of writing subprograms or user defined functions?

6. Explain THREE elements of user defined functions with programming example.

7. Write c program to find factorial of n using user defined function.

8. Write user defined function named isprime(n) that returns 1 if the number is prime; otherwise 0.

9. Write user defined function STRCOPY() to copy string1 into string2.

10. Solve questions from model and annual question papers.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 43

o/p:Enter a string1 to be copy : HappyString copied…String1= Happy String2=Happy

Page 44: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Parameters (Arguments or Inputs) : The inputs given to the functions to do specific task are called parameters or arguments. The parameters are passed by main() to user defined function to process and to get desired result as an output from it. These parameters are classified into following two types.

i) Formal parametersii) Actual parameters

Formal Parameters: The parameters used in the function header of function definition are called formal parameters. These parameters receive input data for processing from the actual parameters from the calling function main(). i,e. formal parameters receive data from actual parameters. The changes made to formal parameters do not affect the contents of actual parameters.Examples:int square(int x); /* Here, x is formal or dummy parameter */void main(){int n,ans;clrscr();printf(“Enter a number:”);ans=square(n); /* Here, n is actual parameter*/printf(“\n square is %s”,ans);getch();}int square(int x) /* Here, x is formal parameter */{return (x*x);}Actual Parameters: The parameters used during the function call in the main() function are called actual parameters. These are actual (original) input data received from users of program and passed to user define function to do specific task. i.e. the contents of actual parameters will be copied into formal parameters.Examples:/* Example for actual parameters */#include<stdio.h>void test(int x,int y);

void main(){int x=7,y=3;clrscr();printf("\n Before calling function: Actual parameters ");printf("\n x=%d y=%d", x,y);test(x,y); /* Here, x & y are actual parameters*/printf("\n After calling function: Actual parameters ");printf("\n x=%d y=%d", x,y);getch();}

void test(int x,int y) /* Here, x & y are formal parameters*/{x++;y++;printf("\n Inside function: Formal parameters");printf("\n x=%d y=%d",x,y);}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 44

o/p:Before calling function: Actual parametersx = 7 y = 3Inside function: Formal parametersx = 8 y = 4After calling function: Actual parametersx = 7 y = 3

Page 45: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Categories of Functions based on number of arguments and return value:

The functions can be categorized into following 4 types based on the number of

parameters or inputs they receive to do specific task and return value.

i. Functions with no arguments and no return value

ii. Functions with arguments and no return value

iii. Functions with arguments and return value

iv. Functions with no arguments and return value

i. Functions with no arguments and no return value:

These functions do not receive any inputs from the calling function main() and do not

return any value back to it. But, these functions do specific task. i.e. there is no data

transmission between calling and called function.

#include<stdio.h>void line(void);void main(){clrscr();line();line();printf("\nVTU,Belagavi.\n");line();line();getch();}void line(void){int i; for(i=1;i<=80;i++) { printf("_"); }}

#include<stdio.h>void sum(void);void main(){clrscr();sum();getch();}void sum(void){int n1,n2,ans;printf("\nEnter two numbers:");scanf("%d%d",&n1,&n2);ans=n1+n2;printf("\nAddition is %d",ans);}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 45

o/p:----------------------------------------------VTU,Belagavi----------------------------------------------

o/p:Enter any two numbers:7 3Addition is 10

Page 46: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

ii. Functions with arguments and no return value:

These functions receive inputs from the calling function main() to do specific task;

but, do not return any value back to it. The processed data will be displayed by it.Example:#include<stdio.h>void sum(int x,int y);void main(){int n1,n2;clrscr();printf("\nEnter two numbers:");scanf("%d%d",&n1,&n2);sum(n1,n2);getch();}void sum(int x,int y){int ans;ans=x+y;printf("\nAddition is %d",ans);}

iii. Functions with arguments and return value:

These functions receive inputs from the calling function main() to process and return

a value back to it. i.e. data transmission takes place between calling and called function.Example:#include<stdio.h>int sum(int x, int y); void main(){int n1,n2,ans;clrscr();printf("\n Enter any two numbers");scanf("%d%d",&n1,&n2);ans=sum(n1,n2); printf("\n Addition is %d",ans);getch();}int sum(int x, int y) {return (x+y);}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 46

o/p:Enter any two numbers:7 3Addition is 10

o/p:Enter any two numbers: 7 3Addition is 10

Page 47: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

iv. Functions with no arguments and return value:

These functions do not receive any inputs from the calling function main(); but, return

a value back to it.

#include<stdio.h>int sum(void);void main(){int ans;clrscr();ans=sum();printf("\nAddition is %d",ans);getch();}int sum(void){int n1,n2;printf("\nEnter two numbers:");scanf("%d%d",&n1,&n2);return(n1+n2);}

Parameter Passing Mechanisms

The mechanism or the process used to send the inputs or values from calling function

main() to user defined function to do specific task is called parameter passing mechanism.

C programmer makes the use of following two methods to pass the values from actual

parameters to formal parameters.

i. Call by value

ii. Call by reference or address

Call by value: This is one of the most commonly used parameter passing mechanism. In this

method, the values are copied from actual parameter to formal parameters and changes made

to formal parameters will not affect the actual parameters. This method returns only one

value back to called function.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 47

o/p:Enter any two numbers: 7 3Addition is 10

Page 48: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Examples:/*Example for call by value method*/#include<stdio.h>void test(int x,int y);

void main(){int x=7,y=3;clrscr();printf("\n Before calling function: Actual parameters ");printf("\n x=%d y=%d", x,y);test(x,y); /* Here, x & y are actual parameters*/printf("\n After calling function: Actual parameters ");printf("\n x=%d y=%d", x,y);getch();}void test(int x,int y) /* Here, x & y are formal parameters*/{x++;y++;printf("\n Inside function: Formal parameters");printf("\n x=%d y=%d",x,y);}

Call by reference: The call by reference method makes the use of pointers to pass the

addresses (references) of actual parameters to user defined function instead of values. In this

method, changes made to formal parameters will affect the actual parameters. This method is

having the capability to return multiple values back to called function, where as pass by

value returns only one value.

Pointer: A pointer is also a variable. It holds only the addresses of other variables. It helps

the programmer to write efficient programs.

Example:

int *ip; /* integer pointer, it holds address of other integer variable*/

int n=7;

ip=&n; /* address of n is stored in integer pointer ip i.e. -12 *//* Working with pointers*/#include<stdio.h>void main(){int *ip;int n=7;clrscr();ip=&n;printf("\n Without using pointer");printf("\n Address of n=%d",&n);printf("\n n=%d",n);printf("\n Using pointer");printf("\n Address of n=%d",ip);printf("\n n=%d",*ip);getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 48

o/p:Before calling function: Actual parametersx = 7 y = 3Inside function: Formal parametersx = 8 y = 4After calling function: Actual parametersx = 7 y = 3

o/p:Without using pointerAddress of n=-12n=7Using pointerAddress of n=-12n=7

Page 49: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

/* Example for call by reference or function to swap two values */

#include<stdio.h>

void swap(int *x,int *y);

void main(){int x=7,y=3;clrscr();printf("\n Before swap or Before calling function \n");printf("\n x=%d y=%d \n",x,y);swap(&x,&y);printf("\n After Swap or After calling function \n");printf("\n x=%d y=%d \n",x,y);getch();}

void swap(int *x, int *y){int temp;temp=*x;*x=*y;*y=temp;}

Differences between Call by value and Call by references methodsSl.No.

Call by value Call by reference

1In this method, the values will be passed from actual to formal parameters.

In this method, the addresses of actual parameters will be passed to formal parameters.

2The changes made to formal parameters will not affect actual parameters.

The changes made to formal parameters will affect actual parameters.

3 Capable to return only one value back to called function.

Capable to return multiple values back to called function.

4 Program execution is slower in comparison with call by reference.

Program execution is faster in comparison with call by value.

5 Pointers knowledge is not required Pointers knowledge is required.

6

Example:

int sum(int x, int y){return(x+y);}

Example:void swap(int *x, int *y){int temp;temp=*x;*x=*y;*y=temp;}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 49

o/p:Before swapx=7 y=3After swapX=3 y=7

Page 50: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Recursive functions “Recursive functions are those functions, in which the function will be called within itself to do some repetitive work repeatedly until certain condition satisfies” The recursive functions are used by programmers to solve those problems in which the next action or calculation depends upon previous result.Example:

To calculate factorial of n. ans =n*fact(n-1) if (n>0)

=1 if (n==0 || n==1)/* to find factorial n by using recursive function*/#include<stdio.h>

long int fact(long int x); /* function declaration*/

void main(){long int n,ans;clrscr();printf("\n Enter a number");scanf("%ld",&n);ans=fact(n); /* function call*/printf("\n Factorial is %ld",ans);getch();}

long int fact(long int n){

if (n==0 || n==1)return(1)

elsereturn (n*fact(n-1));

}

Example 2. Recursive function to find sum of digits of an integer number.

int digitsum(int n){

if (n>9)return(n%10+digitsum(n/10);

elsereturn (n);

}

Example 3. Recursive function to find sum of 1 to n numbers.

int sum(int n){

if (n==1)return(1);

elsereturn (n+sum(n-1));

}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 50

o/p:Enter a number: 4Factorial is 24

Page 51: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Storage classes used in C or Lifetime of variables The lifetime or visibility or accessibility of a variable used in the function depends upon storage class of the variable. The storage classes are classified into following four types.

i. automatic or local or privateii. global or public

iii. staticiv. register

i. automatic variables: These are defined inside the functions and their lifetime is local to the function in which it has been defined. By default, all the variables are of type automatic only. These variables are also called as local or internal variables. The auto keyword can be used to define automatic variables.Example1:void main(){auto int n=7,sq;sq=n*n;printf(“\n Square of %d is %d”, n, sq);}

Example2:/* Example for automatic variables*/#include<stdio.h>void f1(void);void f2(void);void main(){int x=7; /* automatic or local variable*/clrscr();f1();f2();printf("\nx=%d",x);getch();}void f1(void){int x=17; /*local variable*/printf("\nx=%d",x);}void f2(void){int x=177; /* local variable*/printf("\nx=%d",x);}ii. global or public variables: These are defined outside the functions and their lifetime is entire C program including main() and other user defined functions. These are used to share data between many functions in a c program. These are also called as global or public or external variables.

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 51

o/p:x=17x=177x=7

Page 52: Web viewBell Teacher: A new student approached the Zen master and asked how he should prepare himself for his training. "Think of me a bell," the master explained

B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.

Example1:int x=0; /* global variable*/void f1(void)void main(){x++;printf(“\n x=%d”,x);f1()printf(“\n x=%d”,x);getch();}void f1(void){x++;}

iii. static variables: These are defined inside the function with the keyword static. These are visible with the function in which they are defined and entire c program. Once, these variables become active then entire c program they go on updating.Example:void test(void);void main(){int i; for(i=1;i<=3;i++) { test(); }getch();}void test(void)static int x=0; /* static variable*/x++;printf(“\n x=%d”,x);}

iv. register variables: These are defined inside or outside the function by using a keyword register. These variables will occupy space from CPU’s register instead of computer’s primary memory RAM. These variables used to store frequently required data by processors, so that the data stored in register can fetched in less time with higher speed. Example:void main(){register int i, count=0; /* register variables*/clrscr();for(i=1;i<=100;i++){count++;}getch();}

Department of Computer Science and Engineering Class Notes By Mr. Pavan Mahendrakar Page| 52

o/p:x=1x=2

o/p:x=1x=2x=3