Showing posts with label Structure. Show all posts
Showing posts with label Structure. Show all posts

Wednesday, March 3, 2021

C Structure Program On Selection Sort of int Type And char Type Array In Both Order

 Expected Tasks:
- Min of 2 data types to be done (1. int / float  2. Char array ) OR You can also try with array of structures with both data types available in structure.
- Sorting to be done for both data type elements
- Display before and after sorting elements
- validation as per your data elements (Eg. marks cannot be above 100 and below 0 , etc.)
Menu Driven with retaining the array elements as per user's choice, repeat the sorting task are desirable. 

# include  <stdio.h>
#include<string.h>
#include<conio.h>
#define number 10

void iSChar();
void iSInt();
void iSA(int[], int);
void iSD(int [], int);
void display(int [], int);
int check(char *);

int check(char *p)
{
    int i=1;
    char ch;
    while(*p!='\0')
    {
       if(*p>=65 && *p<=90 || *p>=97 && *p<=122 ||*p==' ' || *p=='\n') 
       i=1;
       else
       {
           i=0;
           break;
       }
       p++;
    }
    return i;
    
}

void displayName(char arr[number][50], int n)
{
int i;
printf("\n Sorted list is as follows\n");
for(i = 0; i <n; i++)
printf(" \n%s", arr[i]);
}

void iSInt()
{ 
 int arr[number],choice,i;
for(i=0;i<number;i++)
{
    printf("\nEnter Marks obtained by student no %d: ",i+1);
    scanf("%d",&arr[i]);
    if(arr[i]<0 || arr[i]>100)
    {
        printf("\nEnter marks obtained properly, it can't be %d", arr[i]);
        i--;
        continue;
    }    
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
     iSA(arr, number);
     break;
     case 2:
     iSD(arr,number);
     break;
}
break;
}
}

void iSCA(char name[number][50], int n)
{
int j,i,k;
char temp[50];
for(i = 0 ; i < n-1; i++)
{
    for(j=i+1;j<n;j++)
    {
        if(strcmp(name[i], name[j])>0)
        {
            
       strcpy(temp,name[i]);
        strcpy(name[i], name[j]);
         strcpy(name[j],temp);
        }
    }
    printf("\nAfter pass number %d: ",i+1);
for(k = 0; k <n; k++)
printf("   %s", name[k]);
printf("\n");
}
displayName(name, number);
}

void iSCD(char name[number][50], int n)
{
int j,i,k;
char temp[50];
for(i = 0 ; i < n-1; i++)
{
    for(j=i+1;j<n;j++)
    {
        if(strcmp(name[i], name[j])<0)
        {
            
       strcpy(temp,name[i]);
        strcpy(name[i], name[j]);
         strcpy(name[j],temp);
        }
    }
    printf("\nAfter pass number %d: ",i+1);
for(k = 0; k <n; k++)
printf("   %s", name[k]);
printf("\n");
}
displayName(name, number);
}

void iSChar()
{
    char  name[number][50];
    int choice,i,j=0;
    printf("\nStart Entering Names\n");
for(i=0;i<number;i++)
{
    if(j==0)
    {
        j=1;
      fgets(name[i],50,stdin);
    i--;
    }
    else
    {
        printf("\nEnter Name of student no %d: ",i+1);
    fgets(name[i],50,stdin);
    }
    
    if(!check(name[i]))
    {
        printf("\nEnter Name properly, you have entered %s", name[i]);
        i--;
    }
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
     iSCA(name, number);
     break;
     case 2:
     iSCD(name,number);
     break;
}
break;
}
}

void iSA(int arr[], int n)
{
int j,i,k, temp;
for(i = 0 ; i < n-1; i++)
{
    for(j=i+1;j<n;j++)
    {
        if(arr[i]>arr[j])
        {
            
       temp=arr[i];
       arr[i]=arr[j];
       arr[j]=temp;
        
        }
    }
    printf("\nAfter pass number %d: ",i+1);
for(k = 0; k <n; k++)
printf("   %d", arr[k]);

printf("\n");
}
display(arr, number);
}

void iSD(int arr[], int n)
{
int j,i,k, temp;
for(i = 0 ; i < n-1; i++)
{
    for(j=i+1;j<n;j++)
    {
        if(arr[i]<arr[j])
        {
            
       temp=arr[i];
       arr[i]=arr[j];
       arr[j]=temp;
        
        }
    }
    printf("\nAfter pass number %d: ",i+1);
for(k = 0; k <n; k++)
printf("   %d", arr[k]);

printf("\n");
}
display(arr, number);
}

void display(int arr[], int n)
{
int i;
printf("\n Sorted list is as follows\n");
for(i = 0; i <n; i++)
printf(" %d", arr[i]);
}
void main()
{
int i=1;
char choice;
for(;i;)
{
printf("\nEnter 1 for working on int type array and 2 for char type array:");
choice=getchar();
switch(choice)
{
     case '1':
     iSInt();
     i=0;
     break;
     case '2':
     iSChar();
     i=0;
     break;
     default:
     printf("\nWrong Choice");
}
}
}

Explanation of the program


At start of the program (inside void main (), user choice is taken as this program works on two types - int and char array.If user opts for int type, function 
'iSInt()' is called otherwise 'iSChar()' function is invoked.
if 'iSInt()' is called , inside the function 10 values are stored in an int type array and again user choice is taked for sorting the elements 
in ascending or descending order. For ascending order sorting function ' iSA(arr, number)' is called otherwise ' iSD(arr, number)' is called and after sorting from both the functions, 'display()'
function is called.
For character array, function ' iSChar()' is called and 10 names are stored in a char type array. While taking names fron user another function 'int check (char *)' is called 
to check the validity of the name. Again user choice is taked for sorting the elements 
in ascending or descending order. For ascending order sorting function ' iSCA(arr, number)' is called otherwise ' iSCD(arr, number)' is called and after sorting from both the functions, 'displayName()'
function is called.. ;
x


C Structure Program On Insertion Sort of int Type And char Type Array In Both Order

 Expected Tasks:
- Min of 2 data types to be done (1. int / float  2. Char array ) OR You can also try with array of structures with both data types available in structure.
- Sorting to be done for both data type elements
- Display before and after sorting elements
- validation as per your data elements (Eg. marks cannot be above 100 and below 0 , etc.)
Menu Driven with retaining the array elements as per user's choice, repeat the sorting task are desirable.
 
# include  <stdio.h>
#include<string.h>
#include<conio.h>
#define number 10

void iSChar();
void iSInt();
void iSA(int[], int);
void iSD(int [], int);
void display(int [], int);
int check(char *);

int check(char *p)
{
    int i=1;
    char ch;
    while(*p!='\0')
    {
       if(*p>=65 && *p<=90 || *p>=97 && *p<=122 ||*p==' ' || *p=='\n') 
       i=1;
       else
       {
           i=0;
           break;
       }
       p++;
    }
    return i;
    
}
void displayName(char arr[number][50], int n)
{
int i;
printf("\n Sorted list is as follows\n");
for(i = 0; i <n; i++)
printf(" \n%s", arr[i]);
}

void iSInt()
{
 
 int arr[number],choice,i;
for(i=0;i<number;i++)
{
    printf("\nEnter Marks obtained by student no %d: ",i+1);
    scanf("%d",&arr[i]);
    if(arr[i]<0 || arr[i]>100)
    {
        printf("\nEnter marks obtained properly, it can't be %d", arr[i]);
        i--;
        continue;
    }    
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
     iSA(arr, number);
     break;
     case 2:
     iSD(arr,number);
     break;
}
break;
}
}

void iSCA(char name[number][50], int n)
{
int p,i,k,x;
char temp[50];
for(i = 1 ; i < n; i++)
{
x=0;
p= i -1;
strcpy(temp,name[i]);
while(strcmp(temp, name[p])<0 && p>=0)
{
  strcpy(name[p+1], name[p]);
  p --;
  x++;
}
strcpy(name[p+1], temp);
printf("Step(%d):-", i);
for(k = 1; k <n; k++)
printf(" \n%s", name[k]);
if(x!=0)
printf("-- took %d comparisions to place %s.",x,temp);
else
printf("--No interchange of position for %s.",temp);
printf("\n");
}
displayName(name, number);
}

void iSCD(char name[number][50], int n)
{
int p,i,k,x;
char temp[50];
for(i = 1 ; i < n; i++)
{
x=0;
p= i -1;
strcpy(temp,name[i]);
while(strcmp(temp, name[p])>0 && p>=0)
{
  strcpy(name[p+1], name[p]);
  p --;
  x++;
}
strcpy(name[p+1], temp);
printf("Step(%d):-", i);
for(k = 1; k <n; k++)
printf(" \n%s", name[k]);
if(x!=0)
printf("-- took %d comparisions to place %s.",x,temp);
else
printf("--No interchange of position for %s.",temp);
printf("\n");
}
displayName(name, number);
}

void iSChar()
{
    char  name[number][50];
    int choice,i,j=0;
    printf("\nStart Entering Names\n");
for(i=0;i<number;i++)
{
    if(j==0)
    {
        j=1;
      fgets(name[i],50,stdin);
    i--;
    }
    else
    {
        printf("\nEnter Name of student no %d: ",i+1);
    fgets(name[i],50,stdin);
    }
    
    if(!check(name[i]))
    {
        printf("\nEnter Name properly, you have entered %s", name[i]);
        i--;
    }
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
     iSCA(name, number);
     break;
     case 2:
     iSCD(name,number);
     break;
}
break;
}
}

void iSA(int arr[], int n)
{
int p,temp,i,k,x;
for(i = 1 ; i < n; i++)
{
x=0;
p= i -1;
temp = arr[i];
while(temp < arr[p] && p>=0)
{
  arr[p+1] = arr[p];
  p --;
  x++;
}
arr[p+1] = temp;
printf("Step(%d):-", i);
for(k = 1; k <n; k++)
printf(" %d", arr[k]);
if(x!=0)
printf("-- took %d comparisions to place %d.",x,temp);
else
printf("--No interchange of position for %d.",temp);
printf("\n");
}
display(arr, number);
}

void iSD(int arr[], int n)
{
int p,temp,i,k,x;
for(i = 1 ; i < n; i++)
{
x=0;
p= i -1;
temp = arr[i];
while(temp > arr[p] && p>=0)
{
  arr[p+1] = arr[p];
  p --;
  x++;
}
arr[p+1] = temp;
printf("Step(%d):-", i);
for(k = 0; k <n; k++)
printf(" %d", arr[k]);
if(x!=0)
printf("-- took %d comparisions to place %d.",x,temp);
else
printf("--No interchange of position for %d.",temp);
printf("\n");
}
display(arr, number);
}

void display(int arr[], int n)
{
int i;
printf("\n Sorted list is as follows\n");
for(i = 0; i <n; i++)
printf(" %d", arr[i]);
}

void main()
{
int i=1;
char choice;
for(;i;)
{
printf("\nEnter 1 for working on int type array and 2 for char type array:");
choice=getchar();
switch(choice)
{
     case '1':
     iSInt();
     i=0;
     break;
     case '2':
     iSChar();
     i=0;
     break;
     default:
     printf("\nWrong Choice");
}
}
}

C Structure Program On Merge Sort of int Type And char Type Array In Both Order

Expected Tasks:

- Min of 2 data types to be done (1. int / float  2. Char array ) OR You can also try with array of structures with both data types available in structure.

- Sorting to be done for both data type elements

- Display before and after sorting elements

- validation as per your data elements (Eg. marks cannot be above 100 and below 0 , etc.)


# include  <stdio.h>
#include<string.h>
#include<conio.h>
#define number 10

void iSChar();
void iSInt();
void iQA(int[],int,int);
void iQD(int [], int,int);
void displayL(int [], int);
int check(char *);
 void passA(int [],int ,int );
  void passD(int [],int ,int ); 

int isCorrect (char s[])
{
    int i;
    char ch;
int len=strlen(s);
   int dot=0, sp=0,at=0,let=0; 
   for(i=0;i<len;i++)
   {
    ch=s[i];
    if(ch=='.')
    dot++;
    else if(ch=='@')
    at++;
    else if(ch==' ')
    sp++;
    else if(ch>=65 && ch<=90 || ch>=97 && ch<=122 || ch>=48 && ch<=57)
    let++;
    else
    sp++;
   }
   if(dot==0)
    return 0;
    else if(at==0 || at>1)
    return 0;
    else if(sp>1)
    return 0;
    else
    return 1;
}
void displayID(char arr[number][50], int n)
{
int i;
printf("\n Sorted baggage list is as follows\n");
for(i = 0; i <n; i++)
printf(" \n%s", arr[i]);
}
void iSInt()
{
 
 int arr[number],choice,i;
 printf("\nHere We will enter free baggage one person can carry which must be within 25 kg ");
for(i=0;i<number;i++)
{
    printf("\nEnter baggage weight of person no %d: ",i+1);
    scanf("%d",&arr[i]);
    if(arr[i]<0 || arr[i]>25)
    {
        printf("\nEnter baggage weight properly, it can't be %d - must be within 25 kg", arr[i]);
        i--;
        continue;
    }    
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
     passA(arr, 0,number-1);
     displayL(arr, number);
     break;
     case 2:
     passD(arr, 0,number-1);
     displayL(arr, number);
     break;
}
break;
}
}
 void sortCA(char name[number][50],int top,int size,int bottom)
{
char temp[10][50];
 int f=top;
 int s=size+1;
 int t=top;
 int upper;
 while((f<=size)&&(s<=bottom))
 {
  if(strcmp(name[f],name[s])<=0)
  {
                strcpy(temp[t],name[f]);
                f++;
                }
                else
                {
                  strcpy(temp[t],name[s]);
                 s++;
                }
                t++;
  }
  if(f<=size)
  {
                for(f=f;f<=size;f++)
                {
                  strcpy(temp[t],name[f]);
                 t++;
                 }
  }
  else
  {
                for(s=s;s<=bottom;s++)
                {
                 strcpy(temp[t],name[s]);
                 t++;
                }
  }
  for(upper=top;upper <=bottom;upper++)
  {
                 strcpy(name[upper],temp[upper]);
  }
 }
 void passCA(char name[number][50],int m,int n)
 {
  int i;
  if(m!=n)
  {
                int mid=(m+n)/2;
                passCA(name,m,mid);
                passCA(name,mid+1,n);
                sortCA(name,m,mid,n);
                for(i=0;i<10;i++)
printf("%s ",name[i]);
printf("\n");
  }
 }

void sortCD(char name[number][50],int top,int size,int bottom)
{
char temp[10][50];
 int f=top;
 int s=size+1;
 int t=top;
 int upper;
 while((f<=size)&&(s<=bottom))
 {
  if(strcmp(name[f],name[s])>=0)
  {
                strcpy(temp[t],name[f]);
                f++;
                }
                else
                {
                  strcpy(temp[t],name[s]);
                 s++;
                }
                t++;
  }
  if(f<=size)
  {
                for(f=f;f<=size;f++)
                {
                  strcpy(temp[t],name[f]);
                 t++;
                 }
  }
  else
  {
                for(s=s;s<=bottom;s++)
                {
                 strcpy(temp[t],name[s]);
                 t++;
                }
  }
  for(upper=top;upper <=bottom;upper++)
  {
                 strcpy(name[upper],temp[upper]);
  }
 }
 void passCD(char name[number][50],int m,int n)
 {
  int i;
  if(m!=n)
  {
                int mid=(m+n)/2;
                passCD(name,m,mid);
                passCD(name,mid+1,n);
                sortCD(name,m,mid,n);
                for(i=0;i<10;i++)
printf("%s ",name[i]);
printf("\n");
  }
 }



void iSChar()
{
    char  name[number][50];
    int choice,i,j=0;
    printf("\nStart Entering Email Ids\n");
    fflush(stdin);
for(i=0;i<number;i++)
{
   
        printf("\nEnter email id of member no %d: ",i+1);
    fgets(name[i],50,stdin);
       
    if(!isCorrect(name[i]))
    {
        printf("\nEnter email id properly, you have entered %s", name[i]);
        i--;
    }
 }
 for(;;)
{
printf("\nEnter 1 for ascending order sorting and 2 for descending order sorting:");
scanf("%d",&choice);
if(choice<1 || choice >2)
continue;
switch(choice)
{
     case 1:
    passCA(name, 0,number-1);
     displayID(name, number);
     break;
     case 2:
     passCD(name,0,number-1);
     displayID(name, number);
     break;
}
break;
}
}

void sortD(int arr[],int top,int size,int bottom)
{
 int temp[20];
 int f=top;
 int s=size+1;
 int t=top;
 int upper;
 while((f<=size)&&(s<=bottom))
 {
  if(arr[f]>=arr[s])
  {
                temp[t]=arr[f];
                f++;
                }
                else
                {
                 temp[t]=arr[s];
                 s++;
                }
                t++;
  }
  if(f<=size)
  {
                for(f=f;f<=size;f++)
                {
                 temp[t]=arr[f];
                 t++;
                 }
  }
  else
  {
                for(s=s;s<=bottom;s++)
                {
                 temp[t]=arr[s];
                 t++;
                }
  }
  for(upper=top;upper <=bottom;upper++)
  {
                arr[upper]=temp[upper];
  }
 }
 void passD(int arr[],int m,int n)
 {
  int i;
  if(m!=n)
  {
                int mid=(m+n)/2;
                passD(arr,m,mid);
                passD(arr,mid+1,n);
                sortD(arr,m,mid,n);
                for(i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
  }
 }
 void sortA(int arr[],int top,int size,int bottom)
{
 int temp[20];
 int f=top;
 int s=size+1;
 int t=top;
 int upper;
 while((f<=size)&&(s<=bottom))
 {
  if(arr[f]<=arr[s])
  {
                temp[t]=arr[f];
                f++;
                }
                else
                {
                 temp[t]=arr[s];
                 s++;
                }
                t++;
  }
  if(f<=size)
  {
                for(f=f;f<=size;f++)
                {
                 temp[t]=arr[f];
                 t++;
                 }
  }
  else
  {
                for(s=s;s<=bottom;s++)
                {
                 temp[t]=arr[s];
                 t++;
                }
  }
  for(upper=top;upper <=bottom;upper++)
  {
                arr[upper]=temp[upper];
  }
 }
 void passA(int arr[],int m,int n)
 {
  int i;
  if(m!=n)
  {
                int mid=(m+n)/2;
                passA(arr,m,mid);
                passA(arr,mid+1,n);
                sortA(arr,m,mid,n);
                for(i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
  }
 }
 
 
void displayL(int arr[], int n)
{
int i;
printf("\n Sorted luggage list is as follows\n");
for(i = 0; i <n; i++)
printf(" %d", arr[i]);
}
void main()
{
int i=1;
char choice;
for(;i;)
{
printf("\nEnter 1 for working on int type array and 2 for char type array:");
choice=getchar();
switch(choice)
{
     case '1':
     iSInt();
     i=0;
     break;
     case '2':
     iSChar();
     i=0;
     break;
     default:
     printf("\nWrong Choice");
}
}
getch();
}

Menu Driven C Structure Program Implementing Linear Search and Insertion Sort In Both Orders

 

Create an array of structures for PRODUCT with the following data items:

Product ID

Product Name

Unit Price


a. Get the input from the user, for N Products and display them in a neat format.    

b. Implement Linear Search based on Product Name and display the result.               

c. Implement Insertion Sort based on Price and display the products in a neat format. 



 #include<stdio.h>

 #include<string.h>

struct product

{

 int id;

 float price;

 char item_name [20];

 };

 static int N=4;

 void display(struct product []);

 void intakeValues(struct product []);

  void linearSearch(struct product []);

  void iSA(struct product []);

 void main ()

 { 

  struct product bill[N];

 intakeValues(bill);

 printf("\nItems as entered\n\n");

 printf("\n\n\n");

  display(bill);

 linearSearch(bill);

 iSA(bill);

  getch ();

  }

  void intakeValues(struct product bill[])

  {

   int i;

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

   {

   printf("\nProduct ID: ");

   scanf("%d",&bill[i].id);

   fflush(stdin);

   printf("\nProduct Name: ");

   gets(bill[i].item_name);

   fflush(stdin);

   printf("\nProduct price: ");

   scanf("%f",&bill[i].price);   

  }

}

void display(struct product bill[])

{

int i;

printf("\n        ID           Item Name           Price");

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

   {

printf("\n%10d   %15s   %15.2f", bill[i].id, bill[i].item_name, bill[i].price);

}

}

void linearSearch(struct product bill[])

{

char toSearch[30];

int i,c=0;

fflush(stdin);

printf("\nEnter the product name: ");

gets(toSearch);

printf("\n        ID           Item Name           Price");

printf("\n\n\n");

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

   {

   if(strcmpi(toSearch,bill[i].item_name)==0)

   {

   c++;   

   printf("\n%10d   %15s   %15.2f", bill[i].id, bill[i].item_name, bill[i].price);

   }

   }

if(c==0)

printf("\nNot a single record found");

}

void iSA(struct product bill[])

{

int p,i,k,x,te;

float temp,t;

char tch[30];

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

{

x=0;

p= i -1;

temp = bill[i].price;

while(temp <bill[p].price && p>=0)

{

  t=bill[p+1].price;

  bill[p+1].price = bill[p].price;

  bill[p].price=t;  

  te=bill[p+1].id;

  bill[p+1].id = bill[p].id;

  bill[p].id=te;  

  strcpy(tch,bill[p+1].item_name);

  strcpy(bill[p+1].item_name,bill[p].item_name);

   strcpy(bill[p].item_name,tch);

  p --;

  x++;

}

}

printf("\n\n\nItems sorted on the base of price\n\n");

printf("\n\n\n");

display(bill);

}



Menu-driven program to compare, concatenate, palindrome checking, length calculation, copy strings using structure

 
 #include<stdio.h>
 #include<string.h>
struct string1
{ 
 char str1 [40], str2[20];
 };
 
 void intake(struct string1);
  void compare(struct string1);
  void copy(struct string1);
  void concatenate(struct string1);
  void palindrome(struct string1);
  void len(struct string1);

 void main ()
 { 
  struct string1 obj;
 intake(obj);  
  getch ();
  }

  void palindrome(struct string1 obj)
  {
   int i=0,len;
   while(obj.str1[i]!='\0')
   i++;
   len=i-1;
   i=0;
   while(obj.str1[i]!='\0')
   {
   if(obj.str1[i]!=obj.str1[len])  
    break;
    i++;
    len--;  
   }
  
   if(len==-1)
  printf("\n1st string is palindrome");
  else
  printf("\n1st string is not palindrome");  
 i=0;
   while(obj.str2[i]!='\0')
   i++;
   len=i-1;
   i=0;
   while(obj.str2[i]!='\0')
   {
   if(obj.str2[i]!=obj.str2[len])
  
    break;
    i++;
    len--;  
   }
   if(len==-1)
  printf("\n2nd string is palindrome");
  else
  printf("\n2nd string is not palindrome"); 
 
 } 
  
   void intake(struct string1 obj)
  {  
   printf("\nstring1 No 1: ");
   gets(obj.str1);
   fflush(stdin);
   printf("\nstring1 No 2: ");
   gets(obj.str2);   
   printf("\nStrings as entered\n\n");
 printf("\n\n\n");
  printf("\n   %s   %s", obj.str1, obj.str2);
    palindrome(obj);
    printf("\n\n\n");  
  printf("\nLength of strings\n\n");
    len(obj);    
   printf("\n\n\n");  
  printf("\nCalling compare function\n\n");
    compare(obj);
   printf("\n\n\n");  
  printf("\nCalling concatenate function\n\n");
    concatenate(obj);
     printf("\n\n\n");  
  printf("\nCalling copy function\n\n");
    copy(obj);   
}

void len(struct string1 obj)
{
int i=0,j=0;
while(obj.str1[i]!='\0')
i++;
printf("\nLength of %s is %d",obj.str1,i);
while(obj.str2[j]!='\0')
j++;
printf("\nLength of %s is %d",obj.str2,j);
if(i>j)
printf("\nLength wise %s is greater",obj.str1);
else if(j>i)
printf("\nLength wise %s is greater",obj.str2);
else
printf("\nLength wise both are same");
}

void compare(struct string1 obj)
{
int i=0;
while(obj.str1[i]!='\0')

   {
if(obj.str1[i]!=obj.str2[i])
   break;
  i++;
}
  if(obj.str1[i]>obj.str2[i])
 printf("\n Greater string is %s", obj.str1);
 else if(obj.str1[i]<obj.str2[i])
 printf("\n Greater string is %s", obj.str2);
 else
 printf("\nBoth are same");
}

void copy(struct string1 obj)
{
int i=0;
while(obj.str2[i]!='\0')
   {
   obj.str1[i]=obj.str2[i];  
  i++;
}
  obj.str1[i]='\0';
 printf("\n 2nd string is copied on 1st string");
 printf("\n   %s   %s", obj.str1, obj.str2);  
}

void concatenate(struct string1 obj)
{
int i=0,x=0;
while(obj.str1[i]!='\0')
   {  
  i++;
}   
while(obj.str2[x]!='\0')
  {  
   obj.str1[i]=obj.str2[x];
   i++;
   x++;
  }
  obj.str1[i]='\0';
 printf("\n After concatenation");
 printf("\n   %s  ", obj.str1);
}


Usage of pattern matching algorithm - Naive pattern matching / improved Naive pattern matching / KMP algorithm

 

This is a menu driven program on pattern matching. structure is used here for the pattern matching. 

#include<stdio.h>
#include<string.h>
struct tag
{
char pattern[100];
char text[20];
};
void improved(struct tag obj)  
{  
    char *pat=obj.pattern;
char *txt=obj.text;
int len1 = strlen(pat); 
        int len2 = strlen(txt); 
        int i = 0,j;  
    printf("The text is found in the pattern at the following indices : ");
    while (i<=len1-len2)  
    {  
         for (j = 0; j < len2; j++)  
            if (pat[i + j] != txt[j])  
                break;  
        if (j == len2) 
        {  
            printf(" %d ",i);
            i = i + len2;  
        } 
        else if (j == 0)  
            i = i + 1;  
        else
            i = i + j; 
    }  
}  
void naive(struct tag obj) 
{  
   int array[20];
   int index=-1; 
    char *mainString=obj.pattern;
char *text=obj.text;
   int patLen = strlen(text);
   int strLen = strlen(mainString);
   int i,j;
   for(i = 0; i<=(strLen - patLen); i++)
    {  
      for(j = 0; j<patLen; j++) 
  {  
         if(mainString[i+j] != text[j])
            break;
      }
      if(j == patLen) 
       {     //the text is found     
         array[++index] = i;
      }
   }
   printf("The text is found in the pattern at the following indices : ");
   for(i=0;i<=index;i++)
   printf(" %d",array[i]);
}
void arrange(char* pat, int M, int* pps) 
{
   int length = 0;
   pps[0] = 0;
   int i = 1;
   while (i < M) 
  {
      if (pat[i] == pat[length])
      {
         length++;
         pps[i] = length;
         i++;
      } 
      else 
       {
       if (length != 0)
         length = pps[length - 1];
         else 
        {
            pps[i] = 0;
            i++;
         }
      }
   }
}
void KMP(struct tag obj) 
{
   char* pattern=obj.pattern;
   char* text=obj.text;
   int M = strlen(text);
   int N = strlen(pattern);
   int pps[M];
   arrange(obj.text, M, pps);
   int i = 0;
   int j = 0;
     printf("The text is found in the pattern at the following indices : ");
   while (i < N) 
   {
      if (obj.text[j] == obj.pattern[i]) 
      {
         j++;
         i++;
      }
      if (j == M) 
     {
         printf(" %d", i - j);
         j = pps[j - 1];
      }
      else if (i < N && obj.text[j] != obj.pattern[i])
   {
         if (j != 0)
         j = pps[j - 1];
         else
         i = i + 1;
      }
   }
}
void main() 
{
  struct tag obj;
  int ch,f;
  printf("\nEnter the pattern string (LIKE 'This is a test'): ");
  gets(obj.pattern);
  printf("\nEnter the text string (LIKE 'is'): ");
  gets(obj.text);  
  while(1)
  {
    printf("\nEnter 1 for Naive pattern matching, 2 for improved Naive pattern matching and 3 KMP algorithm: ");
    scanf("%d",&ch);
    f=0;
    switch(ch)
    {
    case 1:
          naive(obj);
          break;
    case 2:
        improved(obj);
        break;
    case 3:
      KMP(obj);
      break;
    default:
    f=1;
     }
    if(f==0)
break; 
 } 
 getch();
}


 Pattern matching is the process of finding a text from a pattern sentence. Different algorithms are used, namely naive pattern checking, improved pattern checking and KMP pattern checking.


Improved naive pattern checking is done by void improved(struct tag obj)  function where char *pat holds the address of the pattern sentence and char *txt holds the address of the text to be searched.

Length of pattern sentence is stored in len1 and that of the text in len2. Inside the loop, the characters of each text are being checked from starting indexes of the both the texts and it is continued till the end of 

the length of the text (which is being searched); If any mismatch found, the search is contined with the starting index of second string with the index of the pattern string where mismatch was found and again the process is continued. 

Whenever no mismatch is found, it means the text is present in the pattern sentence and the staring index is displayed. Next the process is continued with start index of text with the index of the pattern sentence upto which matching was done.


Naive pattern checking is done by void naive(struct tag obj)  function where char *mainstring holds the address of the pattern sentence and char *pattern holds the address of the text to be searched.

Length of pattern sentence is stored in strLen and that of the text in patLen. This technique is also same as improved naive pattern checking with only difference that an array is used to store the starting indexes where the match is found.

Finally the array is displayed.

KMP pattern checking is done by using two functions - void KMP(struct tag obj)  and void arrange(char* pat, int M, int* pps). Inside the arrange function, it is checked whether the characters of the to be searched text are duplicate and if so their indexes are stored in array pps[].  This numeric array is used inside KMP function to search the text in pattern text.

Monday, January 18, 2021

C Program for order billing in a restaurant using an array of structures

 #include< stdio.h >
struct restaurant
{
 int no;
 float total;
 char item [20];
 };
 void main ()
 {
 struct restaurant bill [20];
 int i,x=0,d;
 char ch;
 double tot=0;
    clrscr ();
  printf("\n     Menu Card   \n");
  printf("\n     Item              Price/Plate   \n");
  printf("\n1.   Chicken Byriani  Rs.120   \n");
  printf("\n2.   Mutton Byriani   Rs.150   \n");
  printf("\n3.   Mutton Chap      Rs.100   \n");
    printf("\n4.  Chicken Leg      Rs.75   \n");
    for (i=0;i<20;i++)
    {
   printf ("Enter the Item No: ");
   scanf("%d",&d);
   if(d==1)
strcpy(bill[i].item, "Chicken Byriani");
else if(d==2)
strcpy(bill[i].item, "Mutton Byriani");
else if(d==3)
strcpy(bill[i].item, "Mutton Chap");
else if(d==4)
strcpy(bill[i].item, "Chicken Leg");
    printf ("Enter the number of plates : ");
  scanf ("%d", &bill [i].no);
  if(d==1)
  bill[i].total=bill[i].no*120;
  else if(d==2)
  bill[i].total=bill[i].no*150;
  else if(d==3)
  bill[i].total=bill[i].no*100;
  else if(d==4)
  bill[i].total=bill[i].no*75;
  printf("\nAny More Item (y/n):");
   ch=getche();
   if(ch=='n')
   break;
   }
   x=i+1;
   for(i=0;i<x;i++)
   {
   tot+=bill[i].total;
     printf ("\n%s   %d   %.2f",bill[i].item, bill[i].no, bill[i].total);
   }
    printf("\nTotal Payable Amount: %.2f",tot);

  getch ();

  }


Saturday, May 2, 2015

Structure program on adding two times


#include< stdio.h>
 struct time_struct
 {
  int hr,min,se;
 };
  struct time_struct add(struct time_struct t,struct time_struct t1)
  {
  t.se=t.se+t1.se;
   if(t.se>59)
  {
   t.se=0;
   t.min=t.min+1;
   }
    t.min=t.min+t1.min;
   if(t.min>59)
   {
    t.min=0;
    t.hr=t.hr+1;
   }
   t.hr=t.hr+t1.hr;
    if(t.hr>23)
    {
     t.hr=0;
    }
    return t;
   }
  struct time_struct take(struct time_struct t)
  {
   printf("\nEnter the hour\t");
   scanf("%d",&t.hr);
   printf("\nEnter the minute\t");
   scanf("%d",&t.min);
   printf("\nEnter the second\t");
   scanf("%d",&t.se);
   return t;
  }
 void display(struct time_struct t)
 {
  printf("\nThe time is\t%d%c%d%c%d",t.hr,':',t.min,':',t.se);
 }
  void main()
 {
  struct time_struct t,t1;
  clrscr();
  t= take(t);
  display(t);
  t1= take(t1);
  display(t1);
  t=add(t,t1);
  printf("\nFinal time is\n";
  display(t);
  getch();
 }

Tuesday, February 15, 2011

Use of pointer variables as structure member in C programming


So far we have used normal variables and arrays as structure item or variable. Now we will see how to use pointer variables as structure member.

The following program illustrates the use of pointers in structure.

# include< string.h>
# include< stdio.h>
# include< stdlib.h>
struct Record
{
            char *name;
            char *address;
            long pin;
};

void sort(struct Record *str, int n)
{
            int i,j;
            struct Record temp;
            for(i =0; i <n; i++)
            {
              for (j=i+1; j <n; j++)
              {
               if (strcmp (str[i].name, str[j].name)>0)
               {
                        temp = str[i];
                        str[i] = str[j];
                        str[j] = temp;
               }
              }
             }
}

void main()
{
            char choice;
            int i, n = 0;
            struct Record string[10];
            clrscr();
            printf("Input The List\n ");
            printf("\n**************\n");

do
{
 string[n].name = (char *) malloc(50*sizeof(char));
 string[n].address= (char *) malloc(100*sizeof(char));
printf("Name: ");
gets(string[n].name);
printf("\n Address: ");
gets(string[n].address);
printf("Pin Code: ");
scanf("%ld", &string[n].pin);
n++;
fflush(stdin);
printf("\n Input another y/n? ");
choice = getchar();
fflush(stdin);
}while(choice == 'y');
  printf("Unsorted list \n");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
sort(string, n);
printf("\n Sorted list");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
}

About the program

Name, address and pin number of several persons are stored in the structure type array.  In structure definition two char type pointers are used to store name and address. Locations to store name and address will be created dynamically.
The structure type array is ultimately sored according to names in ascending order and records are displayed.



Monday, February 7, 2011

Structure within Structure in C programming


We have done programs on C structure where structure member are normally primitive data members. Now we will see how to use structure variables as a member of another structure.

#include< stdio.h>
struct cal
{
 int feet;
 float inch;

 };
 struct Room
 {
 struct cal length;
 struct cal width;
 };
 void main()
 {
 struct Room ob;
 float l,w;
    clrscr();
 ob.length.feet=10;
 ob.length.inch=2.5;
 ob.width.feet=10;
 ob.width.inch=2.5;
 l=ob.length.feet+ob.length.inch/12;
 w=ob.width.feet+ob.width.inch/12;
 l=l*w;
 printf("Area of the Room %.2f",l);
  getch();
  }

Another program on structure within structure.

# include< stdio.h>
struct Addr
{
            char street[30];
            char city [30];
            char state[20];
            long  pin;
};
struct Customer
{
            char name[20];
            char account[10];
            char profession[30];
            struct Addr address;
};
void main()
{
   struct Customer *list[100];
   int i, n;
   clrscr();
   printf("\n Input number of record you want to process: ");
   scanf("%d", &n);
   printf("\n Input the information of customer\n");
   for(i=0; i< n; i++)
   {
        fflush(stdin);
       printf("\n Name: ");
       gets(list[i]->name);
       printf("\n Account Number:");
       gets(list[i]->account);
       printf("\n Profession:");
       gets(list[i]->profession);
       printf("\n*** Address***");
       printf("\n**************\n");
       printf("\n Street:");
         gets(list[i]->address. street);
         printf("\n City:");
         gets(list[i]->address. city);
         printf("\n State:");
         gets(list[i]->address. state);
         printf("\n Pin Code:");
         scanf("%ld", &list[i]->address. pin);
         clrscr();
     }

   for(i= 0; i< n; i++)
   {
     printf("\n List of the customer");
     printf("\n ********************\n");
     printf("\n Name: %s", list[i]->name);
     printf("\n Account Number: %s", list[i]->account);
     printf("\n Profession: %s", list[i]->profession);
     printf("\n *** Address ***");
     printf("\n----------------");
     printf("\n Street: %s", list[i]->address. street);
      printf("\n City: %s", list[i]->address. city);
      printf("\n State: %s", list[i]->address. state);
    printf("\n Pin code: %ld", list[i]->address. pin);
    printf("\n*******************");
    printf("\nPress any key...........");
    getch();
     clrscr();
   }
 }

Friday, January 21, 2011

C language Structure program on hotel


About the program

Define a structure that can store details of a hotel. It should have structure members that include the name, address, grade, average room charge and no. of rooms.
Functions of this program will perform the following operations:
Display hotels of a given grade in order of charges.
Display hotels with room charges less than a given value.

Codes of the structure program on hotel

#include< stdio.h>
#include< string.h>
struct s
{
 char name[40],add[40],grade;
 float charge;
 int num;
};
void hot1(struct s *ob,char g,int n)
{
/* this function will display the hotel names of specified grade in order of charge.*/
 int i,j,x=0;
 char final[10][40],dummy[40];
 float r[10],t;
 for(i=0;i<n;i++)
 {
  if(g==ob[i].grade)
  {
   strcpy(final[x],ob[i].name);
   r[x]=ob[i].charge;
   x++;
   }
  }
  for(i=0;i<x;i++)
  {
   for(j=i+1;j<x;j++)
   {
    if(r[i]>r[j])
    {
     t=r[i];
     r[i]=r[j];
     r[j]=t;
     strcpy(dummy,final[i]);
     strcpy(final[i],final[j]);
     strcpy(final[j],dummy);
     }
    }
   }
  puts("Hotel names with specified GRADE in order of charge.");
  for(i=0;i<x;i++)
  {
   printf("\n%s%10.2f",final[i],r[i]);
   }
  }
  void hot2(struct s *ob,float r1,int n)
  {
  /* this function will display hotel names below the specified rate*/
  int i,x=0;
  char final[10][40];
  float r[10];
  for(i=0;i<n;i++)
  {
   if(r1>ob[i].charge)
   {
    r[x]=ob[i].charge;
    strcpy(final[x],ob[i].name);
    x++;
    }
   }
  puts("Hotel names below the specified RATE.");
  for(i=0;i<x;i++)
  {
   printf("\n%s%10.2f",final[i],r[i]);
   }
 }
 void main()
 {
  struct s hotel[10];
  int n,i;
  char g;
  float rate;
  clrscr();
  puts("Enter the  number of hotels(within 10):-");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
   fflush(stdin);
   puts("Enter the hotel name:-");
   gets(hotel[i].name);
   puts("Enter the hotel address:-");
   gets(hotel[i].add);
   puts("Enter the hotel grade:-('a','b','c')");
   scanf("%c",&hotel[i].grade);
   puts("Enter the room charge:-");
   scanf("%f",&hotel[i].charge);
   puts("Enter the room numbers:-");
   scanf("%d",&hotel[i].num);
   clrscr();
  }
  fflush(stdin);
  puts("Now we will search for specific hotels(Press any key)....");
  getch();
  clrscr();
  printf("\nEnter the grade for hotel('a','b','c'):-");
  scanf("%c",&g);
    hot1(hotel,g,n);
    printf("\nPress any key to continue....");
    getch();
  printf("\nEnter the charge:-");
  scanf("%f",&rate);
  puts("\n**************\n");
  hot2(hotel,rate,n);
  getch();
  }


Technical analysis of the above structure program

A structure is defined with number of structure member or elements to store the name of the hotel, address of the hotel, grade of hotels, number of rooms available and average rate.

Structure type array variable is created and the records are stored using for loop. Function ‘void hot1(struct s *,char,int)’ is used to display the hotel names of specified grade in order of charge.

The other function ‘void hot2(struct s *,float ,int )’ displays hotel names below the specified rate as entered by user.

Tuesday, December 28, 2010

Array of structures in C Programming


Today I will discuss about array of structure. Suppose we want to store the test record of our cricket team players (Name, number of test matches played, number of innings, number of not out and total runs scored, average). For this type of program we have to declare a structure with six members and the variable of the structure will be of array type.

program on array of structure 

#include< stdio.h >
struct player
{
 int match, innings, notout, runs;
 float average;
 char name [20];
 };
 void main ()
 {
 struct player play [3];
 int i;
    clrscr ();
    for (i=0;i< 3;i++)
    {
   printf ("Enter the name-");
   scanf ("%s", play [i]. name);
   printf ("Enter the test matches played :-");
  scanf ("%d", &play [i]. match);
   printf ("Enter the test innings played: -");
  scanf ("%d", &play [i]. innings);
   printf ("Enter the not out: -");
  scanf ("%d", &play [i]. notout);
   printf ("Enter the runs scored:-");
  scanf ("%d", &play [i]. runs);
  play [i]. average=(float) play [i]. runs/(play [i]. innings-play [i]. notout);
  }
  printf ("Name Match Innings Not out Runs Average\n");
  for (i=0;i< 3;i++)
  {
  printf ("%s  %d  %d  %d  %d  %.2f\n", play [i]. name, play [i]. match,
  play [i]. innings, play [i]. Notout, play [i]. runs, play [i]. average);
  }
  getch ();
  }

  About the program

‘struct player play [3]’ is the array of structure means the variable play can hold records of three players. Without using the array of structure, we had to create three variables to store the records.

Thursday, December 2, 2010

Use of Pointer in Structure in C programming


C program to illustrates the use of pointers in structure

# include< string.h>
# include< stdio.h>
# include< stdlib.h>
struct Record
{
            char *name;
            char *address;
            long pin;
};
/* This function will be used to sort the list according to name. structure type array variable will be created and address of the  first location and the number of locations, means records will  be passed as argument.*/
void sort(struct Record *str, int n)
{
            int i,j;
            struct Record temp;
            for(i =0; i <n; i++)
            {
              for (j=i+1; j <n; j++)
              {
               if (strcmp (str[i].name, str[j].name)>0)
               {
                        temp = str[i];
                        str[i] = str[j];
                        str[j] = temp;
               }
              }
             }
}
void main()
{
            char choice;
            int i, n = 0;
            struct Record string[10];
            clrscr();
            printf("Input The List\n ");
            printf("\n**************\n");

do
{
 string[n].name = (char *) malloc(50*sizeof(char));
 string[n].address= (char *) malloc(100*sizeof(char));
printf("Name: ");
gets(string[n].name);
printf("\n Address: ");
gets(string[n].address);
printf("Pin Code: ");
scanf("%ld", &string[n].pin);
n++;
fflush(stdin);
printf("\n Input another y/n? ");
choice = getchar();
fflush(stdin);
}while(choice == 'y');
  printf("Unsorted list \n");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
sort(string, n);
printf("\n Sorted list");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
}

Subscribe via email

Enter your email address:

Delivered by FeedBurner