46
SVERI’s College of Engineering, Pandharpur. LAB MANUAL ADVANCED C CONCEPTS Prepared By Prof S.M.Kumbar Prof A.R.Sarkar (Head of Department)

Acc Lab Manual

Embed Size (px)

DESCRIPTION

acc lab manual

Citation preview

Page 1: Acc Lab Manual

SVERI’s

College of Engineering, Pandharpur.

LAB MANUAL

ADVANCED C CONCEPTS

Prepared By

Prof S.M.Kumbar

Prof A.R.Sarkar

(Head of Department)

Page 2: Acc Lab Manual

Sr .No Name of Experiment Page No.

1 Programs to demonstrate storage classes and functions like atoi(),itoa()

and clock() etc.

3-8

2 Program to implement Magic Square by taking size from user. 9-11

3 Program to find Factorial of a number in Fibonacci sequence, Towers of

Hanoi Using recursion.

12-15

4 Program to perform different string operations using string library

functions.

16-19

5 Program to sort the strings alphabetically. 20-21

6 Programs to demonstrate: Array of Pointers, Pointer and Structures,

Dynamic memory.

22-24

7 Programs to simulate string library functions using pointers. 25-27

8 Program to implement Linear search and binary search. 28-29

9 Program to implement selection sort 30-31

10 Program to implement Merge sort 32-33

11 Program to implement Hashing Techniques. 34-35

12 Program to demonstrate file copy operation using command line

arguments.

36-39

Page 3: Acc Lab Manual

Experiment No 1

Programs to demonstrate storage classes and functions like atoi(),itoa() and clock() etc.

Aim: Programs to demonstrate storage classes and functions like atoi(),itoa() and clock()

etc.

Theory:

There are 4 storage class specifies available in C language.

1. auto2. static3. extern4. register

S.No.Storage Specifier

Storage place

Initial / default value

Scope Life

1 autoCPU Memory

Garbage value

local Within the function

2 externCPU memory

Zero Global

Till end of the main program.

Variable definition might be anywhere in the C program

3 staticCPU memory

Zero localRetains the value of the variable between different function calls.

4 registerRegister memory

Garbage value

local Within the function

Page 4: Acc Lab Manual

For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.

Because, register variables are stored in register memory whereas auto variables are stored in main CPU memory.

Only few variables can be stored in register memory. So, we can use variables as register that are used very often in a C program.

Program:

#include<stdio.h>void increment(void); int main(){increment();increment();increment();increment();} void increment(void){auto int i = 0 ; printf ( "%d \n", i ) ; i++; }

Output:0000

 program for C static variable:

//C static example#include<stdio.h>void increment(void); int main(){increment();increment();increment();

Page 5: Acc Lab Manual

increment();} void increment(void){static int i = 0 ; printf ( "%d \n", i ) ; i++; }

Output:0123

program for extern variable:

2

3

4

5

6

7

8

9

#include<stdio.h>

int x = 10 ;

int main( )

{

extern int y ;

printf ( "The value of x is %d \n", x ) ;

printf ( "The value of y is %d",y ) ;

}

int y = 50 ;

Output:

The value of x is 10The value of y is 50

Page 6: Acc Lab Manual

 program for register variable:

#include<stdio.h> int main(){register  int i, arr[5];          // declaring array arr[0] = 10;     // Initializing array arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for (i=0;i<5;i++) {    // Accessing each variable    printf("value of arr[%d] is %d \n", i, arr[i]); }}

 Output:

value of arr[0] is 10value of arr[1] is 20value of arr[2] is 30value of arr[3] is 40value of arr[4] is 50

atoi( ):

it converts ascii(string numbers) into integer numbers.

#include<stdio.h>

main()

{

Char name[10]=”1947”;

Int n;

Page 7: Acc Lab Manual

n=atoi(name);

printf(“%d”,n);

}

Output:

1947

itoa( ):

It converts integer numbers into ascii numbers(string numbers).

#include<stdio.h>

main( )

{

Char name[20]=”10”;

Int n;

Itoa(n,name,16);

Printf(“%s”,name);

}

Output:

A

Page 8: Acc Lab Manual

Clock( ):

It is used measure processor time for execution of program.

Program:

#include<stdio.h>

#include<time.h>

main()

{

float i;

time_t start, end;

start = clock();

// Function here

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

end = clock();

printf("Time was: %lf\n", ((float)(end-start)/CLOCKS_PER_SEC));

}

Output:

0.1623

Page 9: Acc Lab Manual

Experiment no 2

Program to implement Magic Square by taking size from user.

Aim: Program to implement Magic Square by taking size from user.

Theory:

Square is divided into equal number of rows and columns.

1. Start filling each square with the number from 1 to num ( where num = No of Rows X No of Columns )

2. You can only use a number once.3. Fill each square so that the sum of each row is the same as the sum of each column.4. In the example shown here, the sum of each row is 15, and the sum of each column is

also 15.5. In this Example : The numbers from 1 through 9 is used only once. This is called

a magic square.

#include<stdio.h>

Page 10: Acc Lab Manual

#include<conio.h>

void main(){int size,a[4][4];int i,j=0;int sum,sum1,sum2;int flag=0;clrscr();

printf("Enter matrix : ");for(i=0;i<4;i++) { for(j=0;j<4;j++) scanf("%d",&a[i][j]); }

printf("Entered matrix is : nn");for(i=0;i<4;i++){ printf("n"); for(j=0;j<4;j++) { printf("t%d",a[i][j]); }}

//------for diagondal elements---------sum=0;for(i=0;i<4;i++) for(j=0;j<4;j++) { if(i==j) sum=sum+a[i][j]; }//-------------for rows--------------

for(i=0;i<4;i++){ sum1=0; { for(j=0;j<4;j++) sum1=sum1+a[i][j]; } if(sum==sum1) flag=1;

Page 11: Acc Lab Manual

else { flag=0; break; }}//-------------for colomns----------------for(i=0;i<4;i++){ sum2=0; for(j=0;j<4;j++) { sum2=sum2+a[j][i]; } if(sum==sum2) flag=1; else { flag=0; break; }}//----------------------------------------if(flag==1) printf("nntMagic square");else printf("nntNo magic square");//-----------------------------------------getch();}

Output:

printf("Enter matrix : ");

2 9 4

7 5 3

6 1 8 Magic Square

Experiment No-3

Page 12: Acc Lab Manual

Program to find Factorial of a number in Fibonacci sequence, Towers of Hanoi

Using recursion

Aim: Program to find Factorial of a number in Fibonacci sequence, Towers of Hanoi

Using recursion

//a)Factorial of a Number

Program:

#include<stdio.h>

#include<conio.h>

int fact(int );

void main( )

{

int p,q;

printf(“enter value of p”);

scanf(“%d”,&p);

q=fact(p);

printf(“fact=%d”,q);

getch( );

}

int fact(int n)

{

int x,y;

if(n==0)

return(1);

x=n-1;

y=fact(x);

Page 13: Acc Lab Manual

return(n*y);

}

Output:

Enter the value of n=4

Fact=24

// b)Fibonacci sequence

Program:

#include<stdio.h>

#include<conio.h>

int fib ( int );

void main( )

{

int p,q;

printf(“enter value of fibonacci\n”);

scanf(“%d”,&p);

q=fib(p);

printf(“%d”,q);

}

Page 14: Acc Lab Manual

Int fib(int n)

{

int x,y;

if(n<=1)

return (n);

x=fib (n-1);

y=fib (n-2);

return(x+y);

}

Output:

Enter the value =5

3

#include <stdio.h>

void towers(int, char, char, char);

int main()

Page 15: Acc Lab Manual

{

int num;

printf("Enter the number of disks : ");

scanf("%d", &num);

printf("The sequence of moves involved in the Tower of Hanoi are :\n");

towers(num, 'A', 'C', 'B');

return 0;

}

void towers(int num, char frompeg, char topeg, char auxpeg)

{

if (num == 1)

{

printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);

return;

}

towers(num - 1, frompeg, auxpeg, topeg);

printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);

towers(num - 1, auxpeg, topeg, frompeg);

}

Output:

Enter the disk:1

\n Move disk 1 from peg to peg frompeg topeg

Experiment 4:

Program to perform different string operations using string library functions.

Page 16: Acc Lab Manual

Aim: Program to perform different string operations using string library functions.

Theory:

Strings are often needed to be manipulated by programmer according to the need of a

problem. All string manipulation can be done manually by the programmer but, this

makes programming complex and large. To solve this, the C supports a large number of

string handling functions.

There are numerous functions defined in "string.h" header file. Few commonly used string handling functions are discussed below:

String Functions Descriptions

strlen()Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

Program 1:

#include <string.h> main() { char s1[20], s2[20], s3[20]; int x, l1, l2, l3;

Page 17: Acc Lab Manual

printf("\n\nEnter two string constants \n"); printf("?"); scanf("%s %s", s1, s2); /* comparing s1 and s2 */ x = strcmp(s1, s2); if(x != 0) { printf("\n\nStrings are not equal \n"); strcat(s1, s2); /* joining s1 and s2 */ } else printf("\n\nStrings are equal \n"); /* copying s1 to s3 strcpy(s3, s1); /* Finding length of strings */ l1 = strlen(s1); l2 = strlen(s2); l3 = strlen(s3); /* output */ printf("\ns1 = %s\t length = %d characters\n", s1, l1); printf("s2 = %s\t length = %d characters\n", s2, l2); printf("s3 = %s\t length = %d characters\n", s3, l3);

}

Output Enter two string constants ? New York Strings are not equal s1 = NewYork length = 7 characters s2 = York length = 4 characters s3 = NewYork length = 7 characters Enter two string constants ? London London Strings are equal s1 = London length = 6 characters s2 = London length = 6 characters s3 = London length = 6 characters

Page 18: Acc Lab Manual

Program 2:   

#include <stdio.h>int main(){ char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i=0; s1[i]!='\0'; ++i) { s2[i]=s1[i]; } s2[i]='\0'; printf("String s2: %s",s2); return 0;}

OutputEnter String s1: programiz

String s2: programiz-Program 3:

#include <stdio.h>#include <string.h> int main(){ char a[100], b[100];  printf("Enter the first string\n"); gets(a);  printf("Enter the second string\n"); gets(b);  strcat(a,b);  printf("String obtained on concatenation is %s\n",a);  return 0;} Output:

Enter the first string

Hi

Page 19: Acc Lab Manual

Enter the first string

Hello

String obtained on concatenation is Hi Hello

Program 4:

#include<stdio.h>

#include<string.h>

Main( )

{

Char s1[]=”hard”,s2[]=”work”;

If(strcmp(s1,s2)==0)

Printf(“strings are equal”);

Else

Printf(“strings are not equal”);

}

Output:

Strings are not equal.

Experiment No:5

Program to sort the strings alphabetically.

Aim: Program to sort the strings alphabetically.

Page 20: Acc Lab Manual

Theory:Arrange the strings in ascending order.

Program:

#include<stdio.h>

#include<string.h>

int main(){

int i,j,n;

char str[20][40],temp[20];

puts("Enter the no. of string to be sorted");

scanf("%d",&n);

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

gets(str[i]);

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

{

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

{

if(strcmp(str[i],str[j])>0)

{

strcpy(temp,str[i]);

strcpy(str[i],str[j]);

strcpy(str[j],temp);

}

}

}

Page 21: Acc Lab Manual

printf("The sorted string\n");

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

puts(str[i]);

return 0;

}

Output:

Enter the size 3

Enter the strings

Hi

ACC

Welcome

Sorted strings are:

ACC

Hi

Welcome

Experiment 6:

Programs to demonstrate: Array of Pointers, Pointer and Structures, Dynamic memory.

Aim: Programs to demonstrate: Array of Pointers, Pointer and Structures, Dynamic

memory

Pointers can be accessed along with structures. A pointer variable of structure can be

created as below:

Page 22: Acc Lab Manual

struct name { member1; member2; . .};-------- Inside function -------struct name *ptr;

Here, the pointer variable of type struct name is created.

Structure's member through pointer can be used in two ways:

1. Referencing pointer to another address to access memory

2. Using dynamic memory allocation

Consider an example to access structure's member through pointer.

#include <stdio.h>struct name{ int a; float b;};int main(){ struct name *ptr,p; ptr=&p; /* Referencing pointer to memory address of p */ printf("Enter integer: "); scanf("%d",&(*ptr).a); printf("Enter number: "); scanf("%f",&(*ptr).b); printf("Displaying: "); printf("%d%f",(*ptr).a,(*ptr).b); return 0;}

In this example, the pointer variable of type struct name is referenced to the address of p. Then, only the structure member through pointer can can accessed.

Structure pointer member can also be accessed using -> operator.

Page 23: Acc Lab Manual

(*ptr).a is same as ptr->a(*ptr).b is same as ptr->b

Accessing structure member through pointer using dynamic memory allocation

To access structure member using pointers, memory can be allocated dynamically using malloc() function defined under "stdlib.h" header file.

Syntax to use malloc()ptr=(cast-type*)malloc(byte-size)

Example to use structure's member through pointer using malloc() function.

#include <stdio.h>#include<stdlib.h>struct name { int a; float b; char c[30];};int main(){ struct name *ptr; int i,n; printf("Enter n: "); scanf("%d",&n); ptr=(struct name*)malloc(n*sizeof(struct name));/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */ for(i=0;i<n;++i){ printf("Enter string, integer and floating number respectively:\n"); scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b); } printf("Displaying Infromation:\n"); for(i=0;i<n;++i) printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b); return 0;

Page 24: Acc Lab Manual

}

OutputEnter n: 2Enter string, integer and floating number respectively:Programming23.2Enter string, integer and floating number respectively:Structure62.3Displaying InformationProgramming 2 3.20

Structure 6 2.30

EXPERIMENT 7

Programs to simulate string library functions using pointers.

Page 25: Acc Lab Manual

Description:

The strcpy function copies characters from src to dest up to and including the terminating null character.

Return Value

The strcpy function returns dest.

Example

#include <stdio.h>

int main() { char input_str[20]; char *output_str;

strcpy(input_str, "Hello"); printf("input_str: %s\n", input_str);

output_str = strcpy(input_str, "World");

printf("input_str: %s\n", input_str); printf("output_str: %s\n", output_str);

return 0;}

It will proiduce following result:

input_str: Helloinput_str

C - strcmp function

Page 26: Acc Lab Manual

#include <stdio.h>

int strcmp(char *string1, char *string2);

Description:

The strcmp function compares the contents of string1 and string2 and returns a value indicating their relationship.

Return Value

if Return value if < 0 then it indicates string1 is less than string2 if Return value if > 0 then it indicates string2 is less than string1 if Return value if = 0 then it indicates string1 is equal to string2

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

strcpy(string1, "Helloooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

strcpy(string1, "Hellooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

return 0;}

It will proiduce following result:

Return Value is : -111Return Value is : 111Return Value is : 0

Strlen( ):

Page 27: Acc Lab Manual

Description:

The strlen function calculates the length, in bytes, of src. This calculation does not include the null terminating character.

Return Value

The strlen function returns the length of src.

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo");

printf("Length of string1 : %d\n", strlen( string1 )); printf("Length of string2 : %d\n", strlen( string2 ));

return 0;}

It will produce following result:

Length of string1 : 5Length of string2 : 7

Experiment 8

Implementation of Linear Search and Binary search

Program:#include<stdio.h>#include<conio.h>void main(){int a[10],i,key,count=0,n;clrscr();printf("enter the number");

Page 28: Acc Lab Manual

scanf("%d",&n);printf("enter the number of elements to search\n");for(i=0;i<n;i++){scanf("%d",&a[i]);}printf("search the element\n");scanf("%d",&key);for(i=0;i<n;i++){if(key==a[i]){printf("%d present at %d index",key,i);count++;}}if(count==0)

printf("%d element not available\n");getch();}

Output:enter number 5Enter the number of elements to search:10 30 40 50 60Enter the key:5050 is present at index 3

Implementation of Binary Search

Program:#include<stdio.h>#include<conio.h># define size 5void main(){int i,a[size],mid,low=0,key,high=size-1;

Page 29: Acc Lab Manual

clrscr();printf("enter the elements\n");for(i=0;i<size;i++)scanf("%d",&a[i]);printf("enter the key\n");scanf("%d",&key);while(low<=high){mid=(low+high)/2;if(key==a[mid]){printf("%d is present at %d index ",key,mid);}if(key<a[mid])high=mid-1;elselow=mid+1;}getch();}

Output:Enter the elements100 200 300 400 500Enter the key500500 is present at index 4

Experiment 9

Implementation of selection Sort

Program:

#include<stdio.h>

#include<conio.h>

Page 30: Acc Lab Manual

void selectionsort(){int i,j,num,temp;printf("how many elements do you want to sort :\t");scanf("%d",&num);printf("\n Enter the element u want to insert\n ");for(i=0;i<num;i++){scanf("%d",&x[i]);}for(i=0;i<num;i++){for(j=i+1;j<num;j++){if(x[i]>x[j]){temp= x[i];x[i]=x[j];x[j]=temp;}}}printf("\nThe sorted elements are:\n");for(i=0;i<num;i++){printf("%d\t",x[i]);}getch( );}

Output: how many elements you want sort

5

Enter the elements to sort

100

Page 31: Acc Lab Manual

400

300

30

20

Sorted elements are:

20

30

100

300

400

Experiment 10

Implementation of Merge sort

Program:

#include<stdio.h>#define MAX 50

void mergeSort(int arr[],int low,int mid,int high);void partition(int arr[],int low,int high);

Page 32: Acc Lab Manual

int main(){       int merge[MAX],i,n;

    printf("Enter the total number of elements: ");    scanf("%d",&n);

    printf("Enter the elements which to be sort: ");    for(i=0;i<n;i++){         scanf("%d",&merge[i]);    }

    partition(merge,0,n-1);

    printf("After merge sorting elements are: ");    for(i=0;i<n;i++){         printf("%d ",merge[i]);    }

   return 0;}

void partition(int arr[],int low,int high){

    int mid;

    if(low<high){         mid=(low+high)/2;         partition(arr,low,mid);         partition(arr,mid+1,high);         mergeSort(arr,low,mid,high);    }}

void mergeSort(int arr[],int low,int mid,int high){

    int i,m,k,l,temp[MAX];

    l=low;    i=low;    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){

Page 33: Acc Lab Manual

             temp[i]=arr[l];             l++;         }         else{             temp[i]=arr[m];             m++;         }         i++;    }

    if(l>mid){         for(k=m;k<=high;k++){             temp[i]=arr[k];             i++;         }    }    else{         for(k=l;k<=mid;k++){             temp[i]=arr[k];             i++;         }    }       for(k=low;k<=high;k++){         arr[k]=temp[k];    }}

Sample output:

Enter the total number of elements: 5Enter the elements which to be sort: 2 5 0 9 1After merge sorting elements are: 0 1 2 5 9

Experiment 11

Program to implement Hashing and resolving collision using open addressing –Linear probing

#include<stdio.h>#include<conio.h>void main() { int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Page 34: Acc Lab Manual

 int n, value; int temp, hash; clrscr(); printf("\nEnter the value of n(table size):"); scanf("%d", &n); do {  printf("\nEnter the hash value");  scanf("%d", &value);  hash = value % n;  if (a[hash] == 0) {   a[hash] = value;   printf("\na[%d]the value %d is stored", hash, value);  } else {   for (hash++; hash < n; hash++) {    if (a[hash] == 0) {     printf("Space is allocated give other value");     a[hash] = value;     printf("\n a[%d]the value %d is stored", hash, value);     goto menu;    }   }    for (hash = 0; hash < n; hash++) {    if (a[hash] == 0) {     printf("Space is allocated give other value");     a[hash] = value;     printf("\n a[%d]the value %d is stored", hash, value);     goto menu;    }   }   printf("\n\nERROR\n");   printf("\nEnter '0' and press 'Enter key' twice to exit");   }   menu:   printf("\n Do u want enter more");   scanf("%d", &temp);  }  while (temp == 1);  getch();

Page 35: Acc Lab Manual

 }

Experiment 12

C program to implement copy command using command line arguments.

Theory :

A file is a collection of bytes stored on a secondary storage device, which is generally a disk

of some kind. The collection of bytes may be interpreted, for example, as characters, words,

Page 36: Acc Lab Manual

lines, paragraphs and pages from a textual document; fields and records belonging to

a database; or pixels from a graphical image. The meaning attached to a particular file is

determined entirely by the data structures and operations used by a program to process the

file. A file is simply a machine decipherable storage media where programs and data are

stored for machine usage. A text file can be a stream of characters that a computer can

process sequentially. Every file being opened for any operations like :

"r" - Read-Only mode or "r+" - read+write mode.

“w" - Write-Only mode or "w+" - write+read mode.

"a" - Append mode "a+" - read+append mode. 

The variable argc is an argument counter that counts the number of arguments on the

command line. The argv is an argument vector and represents an array of character

pointers that point to the command line arguments. The size of the array will be equal to

argc. For the command line given above, argc is three and argv is an array of three

pointers to string.

The program uses command line arguments to implement the copy command. Three

arguments are taken :

1. the name of the executable file,

2. name to the file to be copied and

3. the name of the file in which it is to be copied.

The file which is to be copied is opened in read mode i.e. in r mode and the file to which it is

to be copied is opened in the write mode i.e in w mode. We are retrieving one character at a

time from the file to be copied then it copies it to the output file. If more than three inputs

are given as arguments, an error message is displayed.

Algorithm :

main(int argc, char*argv[])

{

FILE *source, *target;

/*If arguments are less then 3 then give an error*/

if(argc!=3)

Page 37: Acc Lab Manual

{

print("insufficient argument");

End algorithm;

}

source = fopen(argv[1],"r"); /*open the file in read mode*/

target = fopen(argv[2],"w"); /*open the file in write mode*/

if(source==NULL OR target==NULL)

{

print ("Unable to open..ERROR in opening file");

End algorithm;

}

while((ch=fgetc(source))!=EOF)

write ch to the target file

fclose(source); /*close the source file*/

fclose(target); /*close the target file*/

}

Program listing   :

/* C program to implement copy command */

#include<stdio.h>

#include<string.h>

int main(int argc,char*argv[])

{

FILE *source,*target;

char ch;

/*If arguments are less then 3 then give an error*/

if(argc!=3)

{

printf("Command Error!!Insufficient argument givenn");

return;

Page 38: Acc Lab Manual

}

source=fopen(argv[1],"r");

target=fopen(argv[2],"w");

if(source==NULL || target==NULL)

{

printf("Unable to open..ERROR in opening file!!n");

return;

}

while((ch=fgetc(source))!=EOF)

fputc(ch,target);/*writing to the target file*/

printf("Copy is Successful.n");

fclose(source);

fclose(target);

}

Output :

[user@localhost ~]$ cat abc.txt

I am a student.

I am in 2nd year now.

I love to play computer games.

[user@localhost ~]$ ./a.out abc.txt tmp.txt

Copy is Successful.

[user@localhost ~]$ cat tmp.txt

I am a student.

I am in 2nd year now.

I love to play computer games.