Showing posts with label C Programs. Show all posts
Showing posts with label C Programs. Show all posts

Sunday, March 10, 2024

C Language Recursive Program To Check Palindrome

 #include <stdio.h>
#include <string.h>

int rev(char [], int,int);

int main()
{
   char ch[100];
   printf("Enter a string:");
   scanf("%s",ch);
   printf("\nEntered string is %s",ch);
   int x=rev(ch,0,strlen(ch)-1);
   if(x==1)
   printf("\nPalindrome");
   else
   printf("\nNot Palindrome");
    return 0;
}

int rev(char ch[],int start,int end)
{
   
    if(ch[start]!=ch[end])
    return 0;
    else if(start==end)
    return 1;
    start++;
    end--;
    rev(ch,start,end);
}

C Language Recursive Function Program To Reverse A String

 #include <stdio.h>
#include <string.h>

void rev(char [],int, int);

int main()
{   char ch[100];
   printf("Enter a string:");
   scanf("%s",ch);
   printf("\nEntered string is %s",ch);
 rev(ch,0,strlen(ch)-1); 
      return 0;
}

void rev(char ch[],int i,int end)
{
    char c;
   if(end<=i)
   {
      printf("\nReverse=%s",ch);
       return ;
   }
      c=ch[i];
       ch[i]=ch[end];
       ch[end]=c;
   i++;
   end--;
   rev(ch,i,end);    
}

Sunday, October 15, 2023

C Language Program Finding Factorial Value Using Recursive Function

 #include<stdio.h>

long int fact(int n);

int main() {

    int n;

    printf("Enter a positive integer: ");

    scanf("%d",&n);

    printf("Factorial of %d = %ld", n, fact(n));

    return 0;

}

long int fact(int n) {

    if (n==1)

    return 1;

       int y=fact(n-1);

       return n*y;    

}

Sunday, June 6, 2021

Program To Display Different Combinations Of Entered Values Using C Language

 In this program, five values will be entered by user and different combinations of the numbers will be displayed. In this post, the same program is done using C Language


#include<stdio.h>
void main ()
{
 int i,j,x;
      int arr[5];
    for(i=0;i< 5;i++)
{
         printf("Enter value:");
        scanf("%d",&arr[i]);
    }
    printf("The original valoues are \n");
    for(i=0;i< 5;i++)
    printf(" 5d "+arr[i]);
    printf("\nThe Combination are as follows \n");
    for(i=0;i < 5;i++)
     {
        x=i;
        for(j=0;j< 5;j++)
        {
            printf("%d  "+arr[x]);
            x++;
            if(x> 4)
            x=0;
        }
        printf("\n");
    }
getch();
    }

Arranging values in an array in zig zag manner

 Few values are to be taken from user and the values will be arranged in ascending order but in a zig zag manner. The smallest value will be placed at the extreme left side (at zero index location) and the next value will be at the extreme right location (last index location). Similarly the third value in the ‘1’ index location and 4rth value at the (size-2) location of the array and so on.


#include < stdio.h>
void main()
{
 int c=0,min,minl,k,arr[100],i,j,n,t,x=0,y;
 clrscr();
 printf("\nHow many elements:");
 scanf("%d",&n);
 for(i=0;i< n;i++)
 {
  printf("\nValue=");
  scanf("%d",&arr[i]);
  }
  printf("\nOriginal=");
      for(i=0;i< n;i++)
    printf("%d   ",arr[i]);
  y=n-1;
 for(i=x;i<=y;i++)
 {
  min=arr[i];
  minl=i;
    for(j=i+1;j<=y;j++)
  {
   if(arr[j]< min)
   {
    min=arr[j];
    minl=j;
    }
    }
    if(c%2==0)
    {
     t=arr[x];
     arr[x]=min;
     arr[minl]=t;
     x++;
     }
     else
    {
    t=arr[y];
     arr[y]=min;
     arr[minl]=t;
     y--;
     i--;
     }
     c++;
     }
     printf("\nFinal=");
    for(i=0;i< n;i++)
    printf("%d   ",arr[i]);
    getch();
    }

C Array And Recursive Function To Check Prime Number And Largest Number

 Details of the program: Write a C program that takes a 1-dimensional array arr as input (of size 10) and check if each element in arr is prime or not using recursion, and store the prime numbers in another array arr2

Subtract 2 from each element in arr2
Use recursion to find the largest element in arr2

   
   
   #include<stdio.h>
   int x;
   void main()
   {
    int arr1[10],arr2[10];
    int i;
    for(i=0;i<10;i++)
    {
    printf("\nElement No %d: ",(i+1));
    scanf("%d",&arr1[i]);
    }
    for(i=0;i<10;i++)
{

if(isPrime(arr1[i],arr1[i]/2))

arr2[x++]=arr1[i];
}
printf("\nPrime numbers are\n");
for(i=0;i<x;i++)
printf("%d ",arr2[i]);
for(i=0;i<x;i++)
arr2[i]=arr2[i]-2;

printf("\nAfter Deduction\n");
for(i=0;i<x;i++)
printf("%d ",arr2[i]);
i=getMax(arr2);
printf("\nMax Value=%d",i);
getch();
   }
  int isPrime(int n, int i)
{
    if(i == 1)
        return 1;   
    else
    {
        if(n%i == 0)
            return 0;
        else
            isPrime(n, i-1);    
    }
}
  int getMax(int a[])
{
    static int i = 0, max =- 9999;  
    if(i < x)   
    {
        if(max < a[i])
        max = a[i];
        i++;    
        getMax(a);   
    }
    return max;
}

2 D Array C Program

 Details of the program: Write a C program that takes a 2-dimensional array arr as input (of size 4 x 4),  multiply all the even elements in arr and store in a variable mult  check if multiplying any two elements in arr equals mult. Check this for all possible pairs.

 If any pair equals mult, print those pairs.

Otherwise, print “No pair found”

#include<stdio.h>
void main()
{

int arr[4][4];
int i,j,n,m,mult=1,p=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("\nValues:");
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]%2==0)
mult=arr[i][j]*mult;
}
}
printf("\nMatrix as follows\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
printf("%d ",arr[i][j]);
printf("\n");
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]%2==0)
{

for(n=i;n<4;n++)
{
for(m=j;m<4;m++)
{
if(arr[n][m]%2==0 && arr[n][m]*arr[i][j]==mult)
{
printf("\n Pair %d  %d",arr[i][j], arr[n][m]);
p=1;
}
}
}
}
}
}
if(p==0)
printf(" Pair Not Found");
getch();
}

C Array And Sorting

 Details of the program:  Write a C program that Takes a 1-dimensional array a as input (of size 20)
Now, sort the first 5 elements in descending order and sort the last 15 elements in ascending order (do not use any pre-defined function for sorting) in a using at most 2 loops. Replace the smallest element with -1 without using any more loop and display the final array elements

#include<stdio.h>
void main()
{

int arr[20];
int i,j,t,min,index;
for(i=0;i<20;i++)
{
printf("\nValues:");
scanf("%d",&arr[i]);
 
}
for(i=0;i<5-1;i++)
{
for(j=i+1;j<5;j++)
{
if(arr[i]<arr[j])
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
for(i=5;i<20-1;i++)
{
for(j=i+1;j<20;j++)
{
if(arr[i]>arr[j])
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
if(arr[4]<arr[5])
arr[4]=-1;
else
arr[5]=-1;
printf("\nElements as follows\n");
for(i=0;i<20;i++)
printf(" %d",arr[i]);
getch();
}

Output Of C Language Codings

 
#include<stdio.h>
int x;
int fun(int);
void main()
{
printf("%d", fun(10));
getch();
}
int fun(int z)
{
if(z<=3)
return (z++);
else
return ((--z)*x);
}
output 0

#include<stdio.h>
int *func(int *a, int b)
{

*a+=20;
b-=10;
return a;
}
void main()
{
int *x, y=9,z=19;
x=func(&y,z);
printf("%d %d %d",*x,z,y);
getch();
}
output: 29 19 29

#include<stdio.h>
void main()
{
int d=9,a=7,e=6;
float c=2.5,f=-3.5;
printf("%f", ++a>(a--+e++)||(d==c+f)&& !(a<c));
getch();
}
output: 0.000000

#include<stdio.h>
void main()
{
int x=4,y=-2,z;
while(0<x)
{
x--;
y++;
if(x!=y)
printf("\n%d %d",x,y);
else
continue;
}
getch();
}
OUTPUT
3 -1
2 0
0 2

#include<stdio.h>
#include<string.h>
void main()
{
char s1[30];
strcpy(s1,"#CP Exam#");
char s2[30];
strcpy(s2,"$CP Exam$");
if(printf(s2)!=strlen(s1))
printf("final");
else if(printf(s1)==strlen(s1))
printf("end term");
else
printf("compre");
getch();
}
output: $CP Exam$#CP Exam#end term

#include<stdio.h>
void main()
{
int i=9,j=7;
float x=2.5,y=-3.5,c;
c=(i-5*++x)/(y--+8*j)/++y-x;

printf("\n%f",c);

getch();
}
Output: -3.45

#include<stdio.h>
int fun (int);
void main()
{
int x=8;
int fun(int x);
printf("\n%d",fun(x));

getch();
}
int fun(int x)
{
if(x>0)
return (x+fun(x-2));
}
Output: 20



#include<stdio.h>
int fun (int arr[3][])
{
arr[1][2]=3;
int i=0,j=0;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf("%d",arr[i])[j]);
}
void main()
{
int arr[3][4]={0};
fun(arr);

getch();
}
Output: Compilation Error

#include<stdio.h>
void main()
{
char ch;
char check[12]={1,2,4,5,8,9,22,77,55};
ch=(check+1)[5];
printf("\n%d",ch);

getch();
}
Output: 22


#include<stdio.h>
#include<string.h>
void main()
{
char s1[20]="BITS";
char s2[20]="2021";

printf("\n%s",strcpy(s2,strcat(s1,s2)));

getch();
}
Output: BITS2021


#include<stdio.h>
void main()
{
int x=2;
switch(x+1,x-1)
{
case 1:
printf("BITS");
case 2:
printf("2021");
default:
printf("BITS2021");
}

getch();
}
Output:
BITS2021BITS2021


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 16, 2015

indexof function in C Language program


There is no predefined indexof function in C Language. We will define a function named indexof in C language which will show the position of a character in a string.

 There will be two different indexof functions, one will take the original string as first argument and a character as the second argument. The function will show the first occurrence index location of the character in the string. If the character is not found in the string, the function will return =1.


  The second one will take the original string as first argument and a character as the second argument and an index as the third argument. The function will show the first occurrence index location of the character in the string after the specified index (3rd argument). If the character is not found in the string, the function will return =1.

  PROGRAM 1:

#include< string.h>
#include< stdio.h>
int indexof(char *,char);
 void main()
 {
  char ch[100];
  char c;
  int i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  i=indexof(ch,c);
  if(i< 0)<0 o:p="">
  printf("\nThe character %c is not present in string %s",c,ch);
  else
    printf("\nThe character %c is in index %d in string %s",c,i,ch);
  getch();
  }
int indexof(char *p,char c)
{
int i=0;
 while(*p!=NULL)
 {
 if(c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;
 }


PROGRAM 2


#include< string.h>
#include< stdio.h>
int indexof(char *,char,int);
 void main()
 {
  char ch[100];
  char c;
  int x,i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  printf("\nEnter the location after which the character to search:");
 scanf("%d",&i);
  x=indexof(ch,c,i);
 if (x< 0)
   printf("\nThe character %c is not present in string %s after index %d",c,ch,i);
  else
    printf("\nThe character %c is in index %d after index %d in string %s",c,x,i,ch);
  getch();
  }
int indexof(char *p,char c,int x)
{
int i=0;
 while(*p!=NULL)
 {
 if(i > x && c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;

 }

Friday, May 15, 2015

substring function in C Language program


There is no predefined substring function in C Language. We will define a function named substring in C language which will extract a part of the string from the original string.

 There will be two different substring functions, one will take the original string as first argument and an index of the string as the second argument. A part of the string from the location specified by the index value of the string upto the end of the string will be extracted.

  The second substring function will take the original string as first argument, an index of the string as the second argument and number of characters as the third argument. The function will extract a substring from the original string of specified characters (3rd argument) starting from the starting index (2nd argument).


  PROGRAM 1:

#include< string.h>
#include< stdio.h>
char * substring(char *,int);
 void main()
 {
  char ch[100];
  int i;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
 ptr=substring(ch,i);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i)
 str[x++]=*p;
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }

 PROGRAM 2


#include< string.h>
#include< stdio.h>
char * substring(char *,int,int);
 void main()
 {
  char ch[100];
  int i,j;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
  printf("\nEnter the number of characters to extract:");
  scanf("%d",&j);

 ptr=substring(ch,i,j);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i,int j)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i && c str[x++]=*p)
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }


Saturday, May 2, 2015

C Program on Union


#include
union tag
{
 int a;
 char ch;
 };
 void main()
 {
  union tag ob;
  clrscr();
  printf("\nEnter age:");
  scanf("%d",&ob.a);
  printf("\nEntered age=%d",ob.a);
  ob.ch='m';
  printf("\nGender=%c",ob.ch);
   printf("\nNow age=%d",ob.a);
  getch();
  }

  Just watch the output, if you have entered 20 as age, the first output will show 20 next you have set value 'm' on union member 'ch'. As union members share the same location, so the age value is destroyed.

 Output for gender will display 'm' but the third output will show wrong value.

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();
 }

Subscribe via email

Enter your email address:

Delivered by FeedBurner