C Program of reversing a string using stack


 

/*Program of reversing a string using stack */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX 20

int top = -1;
char stack[MAX];
char pop();
void push(char);

main()
{
char str[20];
unsigned int i;
printf(“Enter the string : ” );
gets(str);
/*Push characters of the string str on the stack */
for(i=0;i<strlen(str);i++)
push(str[i]);
/*Pop characters from the stack and store in string str */
for(i=0;i
str[i]=pop();
printf(“Reversed string is : “);
puts(str);
}/*End of main()*/

void push(char item)
{
if(top == (MAX-1))
{
printf(“Stack Overflow\n”);
return;
}
stack[++top] =item;
}/*End of push()*/

char pop()
{
if(top == -1)
{
printf(“Stack Underflow\n”);
exit(1);
}
return stack[top–];
}/*End of pop()*/

 

Infix to Postfix Expression conversion using stacks


 

Illustration of infix notation
Illustration of infix notation (Photo credit: Wikipedia)

Here is and application of stacks in data structures in the conversion of infix to postfix expression

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>

#define N 64

#define LP 10

#define RP 20

#define OPERATOR 30
#define OPERAND 40

#define LPP 0
#define AP 1
#define SP AP
#define MP 2
#define DP MP
#define REMP 2

#define NONE 9

static char infix[N+1],stack[N],postfix[N+1];
static int top;

void infixtopostfix(void);
int gettype(char);
void push(char);
char pop(void);
int getprec(char);
main()
{
char ch;
do
{
top=-1;
printf(“\nEnter an infix expression\n”);
fflush(stdin);
gets(infix);
infixtopostfix();
printf(“\ninfix = %s\npost fix =%s\n”,infix,postfix);
printf(“\nDo you wish to continue\n”);
ch=getche();
}while(ch==’Y’ || ch==’y’);
}

void infixtopostfix(void)
{
int i,p,l,type,prec;
char next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP:
push(infix[i]);
break;
case RP:
while((next=pop())!='(‘)
postfix[p++]=next;
break;
case OPERAND:
postfix[p++]=infix[i];
break;
case OPERATOR:
prec=getprec(infix[i]);
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}
while(top>-1)
postfix[p++]=pop();
postfix[p]=”;
}

int gettype(char sym)
{
switch(sym)
{
case ‘(‘:
return(LP);
case ‘)’:
return(RP);
case ‘+’:
case ‘-‘:
case ‘*’:
case ‘/’:
case ‘%’:
return(OPERATOR);
default :
return(OPERAND);
}
}

void push(char sym)
{
if(top>N)
{
printf(“\nStack is full\n”);
exit(0);
}
else
stack[++top]=sym;
}

char pop(void)
{
if(top<=-1)
{
printf(“\nStack is empty\n”);
exit(0);
}
else
return(stack[top–]);
}

int getprec(char sym)
{
switch(sym)
{
case ‘(‘:
return(LPP);
case ‘+’:
return(AP);
case ‘-‘:
return(SP);
case ‘*’:
return(MP);
case ‘/’:
return(DP);
case ‘%’:
return(REMP);
default :
return(NONE);
}
getch();
}

\n

String Pattern Matching in C using pointers


 

Block diagrams of (Left) pattern matching and ...
Block diagrams of (Left) pattern matching and substitution method and (Right) soft pattern matching method. (Photo credit: Wikipedia)

 

String Pattern Matching Program in C using Pointers

 

Its an application of Arrays

 

 

#include<stdio.h>
#include<conio.h>
int match(char*, char*);

main()
{
char a[100], b[100];
int position;

printf(“Enter some text\n”);
gets(a);

printf(“Enter a string to find\n”);
gets(b);

position = match(a, b);

if(position!=-1)
printf(“Found at location %d\n”, position+1);
else
printf(“Not found.\n”);

getch();
}

int match(char *a, char *b)
{
int c;
int position = 0;
char *x, *y;

x = a;
y = b;

while(*a)
{
while(*x==*y)
{
x++;
y++;
if(*x==”||*y==”)
break;
}
if(*y==”)
break;

a++;
position++;
x = a;
y = b;
}
if(*a)
return position;
else
return -1;
}

 

 

 

\n

 

String concatenation in c without using strcat Function


#include
#include

void stringConcat(char[],char[]);
int main()
{
char strl[100],str2[100];
int compare;
clrscr();
printf(“\nEnter first string: \n”);
scanf(“%s”,strl);
printf(“\nEnter second string: “);
scanf(“%s”,str2);
stringConcat(strl,str2);
printf(“\nString after concatenation: %s”,strl);
return 0;
getch();
}

void stringConcat(char strl[],char str2[])
{
int i=0,j=0;
while(strl[i]!=”)
{
i++;
}
while(str2[j] ! = ”)
{
strl[i] = str2[j] ;
i++;
j++;
}

strl[i] = ‘ ‘;
}

Program to Count Blanks Spaces ,Tabs and Newlines in Given String In C


#include<stdio.h>

int main(void)
{
 int nb,nt,nl,c;
 nb=nt=nl=0;

 while((c=getchar())!=EOF)
 {
  if(c==’ ‘)
   ++nb;
  if(c==’ ‘)
   ++nt;
  if(c==’ ‘)
   ++nl;
 }

 printf(“No. of Blanks is %d,No. of Tabs is %d and No. of Newlines is %d”,nb,nt,nl);

return 0;
}

C Program to mask password text with *


#include <stdio.h>
#include <conio.h>
 
void main()
{
 char pasword[10],usrname[10], ch;
 int i;
 
 clrscr();
 
 printf("Enter User name: ");
 gets(usrname);
 printf("Enter the password <any 8 characters>: ");
 
 for(i=0;i<8;i++)
 {
  ch = getch();
  pasword[i] = ch;
  ch = '*' ;
  printf("%c",ch);
 }
 
 pasword[i] = '';
 
 /*If you want to know what you have entered as password, you can print it*/
 printf("\nYour password is :");
 
 for(i=0;i<8;i++)
 {
  printf("%c",pasword[i]);
 }
}

C Program TO FIND OR COUNT TOTAL NUMBER OF PALINDROME IN A GIVEN STRING



#include<stdio.h>
#include<string.h>
int stpal(char str[50], int st, int ed);
void main()
{
char str[50];
int pal = 0, len = 0, i, start = 0, end;
clrscr();
printf("\n\n\t ENTER A SENTENCE...: ");
gets(str);
while(str[len]!='')
len++;
len--;
for(i=0;i<=len;i++)
{
if((str[i] == ' ' && str[i+1] != ' ') || i == len)
{
if(i == len)
end = i;
else
end = i - 1;
if( stpal (str, start, end ) )
pal++;
start = end + 2;
}
}
printf("\n\n\t THE TOTAL NUMBER OF PALINDROMES ARE..: %d",pal);
getch();
}
int stpal(char str[50], int st, int ed)
{
int i, pal=0;
for(i=0; i<=(ed-st)/2; i++)
{
if(str[st+i] == str[ed-i])
pal = 1;
else
{
pal = 0;
break;
}
}
return pal;
}

C Program To Display The Days In A Week.


#include <stdio.h>
#include<conio.h> 
void main()
{
char ch;
clrscr();
printf(" Enter m for Monday\n t for Tuesday\n w for Wednesday\n h for Thursday\n f for Friday\n s for Saturday\n u for Sunday ");

scanf(" %c ", &ch);

switch(ch)
{
case 'm':
case 'M':
printf("The day is Monday");
break;

case 't':
case 'T':
printf("The day is Tuesday");
break;

case 'w':
case 'W':
printf("The day is Wednesday");
break;

case 'h':
case 'H':
printf("The day is Thursday");
break;

case 'f':
case 'F':
printf("The day is Friday");
break;

case 's':
case 'S':
printf("The day is Saturday");
break;

case 'u':
case 'U':
printf("The day is Sunday");
break;

default :
printf("Wrong input!");
break;
}
getch();

}

Convert string to int without using library functions in c



#include<stdio.h>

int stringToInt(char[] );
int main()
{
char str[10];
int intValue;
printf("Please Enter any integer as a string: ");
scanf("%s",str);
intValue = stringToInt(str);
printf("Equivalent integer value: %d",intValue);
return 0;
}

int stringToInt(char str[])
{
int i=0,sum=0;
while(str[i]!=''){
if(str[i]< 48 || str[i] > 57){
printf("Unable to convert it into integer.\n");
return 0;
}
else
{
sum = sum*10 + (str[i] - 48);
i++;
}

}

return sum;

}

Integer to english string program in c++


#include <string.h>
#include <iostream.h>

using namespace std;

string num_to_text[] = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };

string tens_to_text[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

string power_to_text[] = { "", "thousand", "million", "billion" };

string padIfNeeded (string ans)
{
if ( ans == "" )
{
return "";
}
return " " + ans;
}

string translateHundred (int hundred_chunk)
{
// handle special cases in the teens
if ( hundred_chunk < 20 ) {
return num_to_text[ hundred_chunk ];
}
int tens = hundred_chunk / 10;
int ones = hundred_chunk % 10;
return tens_to_text[ tens ] + padIfNeeded( num_to_text[ ones ] );
}


string translateThousand (int thousand_chunk)
{
if ( thousand_chunk < 100 )
{
return translateHundred( thousand_chunk );
}
else
{
int hundreds = thousand_chunk / 100;
int hundred_chunk = thousand_chunk % 100;
return num_to_text[ hundreds ] + " hundred" + padIfNeeded( translateHundred( hundred_chunk ) );
}
}


int main()
{
int n;
cin >> n;
string number;
bool is_negative = false;
if ( n < 0 )
{
is_negative = true;
n *= -1;
}

int chunk_count = 0;
while ( n > 0 )
{
if ( n % 1000 != 0 ) {
number = translateThousand( n % 1000 ) + padIfNeeded( power_to_text[ chunk_count ] + padIfNeeded( number ) );
}
n /= 1000;
chunk_count++;
}
if ( number == "" )
{
number = "zero";
}
if ( is_negative )
{
number = "negative " + number;
}
cout >> number >> endl;
}

C program to convert the number entered into words as in cheques etc…



#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<conio.h>
char *ordinal (char buf[1024], int value);
int main (int argc, char *argv[])
{
clrscr();
char buf[1024];
if (argc != 2)
{
printf(“usage: ordinal <number>\n”);
return EXIT_FAILURE;
}
ordinal (buf, atoi (argv[1]));
puts (buf);
getch();
return EXIT_SUCCESS;


}
/* Works for positive and negative numbers up to 9 digits long,
if you speak American English. */
char *ordinal (char buf[1024], int value)
{
static const char *const powers[]={“thousand”, “million”, “billion”};
static const char *const ones[]={“one”, “two”, “three”, “four”, “five”,
“six”, “seven”, “eight”, “nine”, “ten”,
“eleven”, “twelve”, “thirteen”, “fourteen”, “fifteen”,
“sixteen”, “seventeen”, “eighteen”, “nineteen”};
static const char *const tens[]={“twenty”, “thirty”, “forty”, “fifty”,
“sixty”, “seventy”, “eighty”, “ninety”};
char *cp = buf;
if (value < 0)
{
cp += sprintf (cp, “negative “);
value = -value;
}
else if (value == 0)
{
strcpy (buf, “zero”);
getch();
return buf;


}
{
int part_stack[4];
int *part_ptr = part_stack;
for (; value; value /= 1000)
*part_ptr++ = value % 1000;
while (part_ptr > part_stack)
{
int p = *–part_ptr;
if (p >= 100)
{
cp += sprintf (cp, “%s hundred “, ones[p / 100 – 1]);
p %= 100;
}
if (p >= 20)
{
if (p % 10)
cp += sprintf (cp, “%s-%s “, tens[p / 10 – 2], ones[p %
10 – 1]);
else
cp += sprintf (cp, “%s “, tens[p / 10 – 2]);
}
else if (p > 0)
cp += sprintf (cp, “%s “, ones[p – 1]);
if (p && part_ptr > part_stack)
cp += sprintf(cp, “%s “, powers[part_ptr – part_stack – 1]);
}
}
cp[-1] = 0;
return buf;
}


C Program to TO REVERSE THE GIVEN STRING using Pointers


#include<stdio.h>
#include<conio.h>
void strev(char *str1, char *str2);

main()
{
char *str1, *str2;
printf("\n\n\t PLZ ENTER A STRING...: ");
gets(str1);
strev(str1,str2);
printf("\n\t YOUR THE REVERSED STRING IS...: ");
puts(str2);
getch();
}
void strev(char *str1, char *str2)
{
int i = 0, len = 0, r = 0;
while(*(str1+len)!='')
len++;
for(i=len-1; i>=0; i--)
{
*(str2+r) = *(str1+i);
r++;
}
*(str2+r) = '';
}

C PROGRAM TO PRINT A STRING HORIZONTALLY AND VERTICALLY


#include <stdio.h>
#include<conio.h>
                 main()
                 {
                 char str[40] = “Today is Monday.”;
                 int i;

                 for(i = 0 ; str[i] != ” ; i++)
                 {
                 printf(“\n%c”, str[i]);
                  }

                 printf(“\n%s”, str);  
                 getch();
                 }

C PROGRAM TO PRINT THE EQUIVALENT POSTION OF THE CHARECTERS IN THE STRING ACCORDING TO ALPHBETS


#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    int i,j,k=0,c=97,n=0,d[50];
    char a[50];
    printf(“Enter any String\n\n”);
    gets(a);
    strlwr(a);
    int l=strlen(a);
    for(i=0;i<l;i++)
    {
    for(j=97;j<122;j++)
    {
    n=(int)a[i];                
    if(n==j)
    {
    k=j-96;
    printf(“%d\t”,k);
    }
    }
    }
    getch();
}    

STRING MANIPULATION PROGRAM LIKE TOGGLE CASE AND TITLE CASE


#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
      int i,len,num=0,ch=0;
      char a[50],b;
     
      printf(“================================================”);
      printf(“\n          STRING MANIPULATION”);
      printf(“\n================================================”);
      printf(“\nEnter any string :\n “);
      gets(a);
      len=strlen(a);
      printf(“\nchoose from below the task to done :”);
      printf(“\n 1. to convert the string too lower case “);
      printf(“\n 2. to convert the string too upper case “);
      printf(“\n 3. to convert the string too title case “);
      printf(“\n 4. Display achromatic string “);
      printf(“\nEnter your Choice= “);
      scanf(“%d”,&ch);
      switch(ch)
      {
                case 1:
                     for(i=0;i<len;i++)
                     {
                        num=(int)a[i];
                        if((num>=65)&&(num<=90))
                        {
                           num=num+32;
                           printf(“%c”,num);
                           num=0;
                        }
                        else if(num==32)
                        printf(” “);
                        else if((num>=97)&&(num<=122))
                        printf(“%c”,num);
                        else
                        printf(“%s”,a[i]);
                     }
                     break;
                   
                case 2:    
                     for(i=0;i<len;i++)
                     {
                        num=(int)a[i];
                        if(num>=97&&num<=122)
                        {
                           num=num-32;
                           printf(“%c”,num);
                           num=0;
                        }
                        else if(num==32)
                        printf(” “);
                        else if((num>=65)&&(num<=90))
                        printf(“%c”,num);
                        else
                        printf(“%s”,a[i]);
                     }
                     break;
               
                case 3:
                     printf(“\nDemonstration of title case “);
                     b=a[0];
                     if(b>=’a’&&b<=’z’)
                     {
                        num=(int)b-32;
                        printf(“%c”,num);
                        num=0;
                     }
                     else
                     {
                        printf(“%c”,b);
                        b=”;
                     }
                     for(i=1;i<len;i++)
                     {
                        if(a[i]==’ ‘)
                        {
                           b=a[i+1];
                           num=(int)b;
                           if(num>=97&&num<=122)
                           {
                              num=num-32;
                              printf(“%c”,num);
                              num=0;
                           }
                        }
                        else
                        printf(“%s”,a[i]);
                     }
                     break;
               
                case 4:
                     b=a[0];
                     printf(“%c.”,b);
                     i=1;
                     while(i<len)
                     {
                       if(a[i]==’ ‘)
                       {
                           b=a[i+1];
                           printf(“%c.”,b);
                       }
                       i++;
                     }
                     break;                            
               
                default:
                printf(“\nWRONG CHOICE 404 ERROR FILE NOT FOUND”);
      }                              
     
      getch();
      }

to replace all the first charecters of words in a sentance with a vowel in sequence


#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
main()
{
      int i,l,j=0;
      char a[50],b[5]={‘e’,’i’,’o’,’u’};
      cout<<“enter any string:-“;
      gets(a);
      l=strlen(a);
      strlwr(a);
      a[0]=’a’;
      for(i=0;i<l;i++)
      {
            if(a[i]==’ ‘){
            a[i+1]=b[j];
            j++;}
            else
            continue;
      }
      cout<<“new string is=”<<a;
      getch();
}        
   

C PROGRAM TO FIND THE TOTAL NUMBER OF PALINDROME IN A GIVEN STRING


/*PROGRAM TO FIND THE TOTAL NUMBER OF PALINDROME IN A GIVEN STRING*/
#include<stdio.h>
#include<conio.h>
int stpal(char str[50], int st, int ed);
main()
{
char str[50];
int pal=0,len=0,i,start=0,end;

printf(“\n—————————————————————-“);
printf(“\n\nPROGRAM TO FIND THE TOTAL NUMBER OF PALINDROME IN A GIVEN STRING”);
printf(“\n—————————————————————-“);
printf(“\n\nENTER A SENTENCE…: “);
gets(str);
while(str[len]!=”)
len++;
len–;
for(i=0;i<=len;i++)
{
if((str[i]==’ ‘&&str[i+1]!=’ ‘)||i==len)
{
if(i==len)
end=i;
else
end=i-1;
if(stpal(str,start,end))
pal++;
start=end+2;
}
}
printf(“\n\n\t THE TOTAL NUMBER OF PALINDROMES ARE..: %d”,pal);
printf(“\n\n—————————————————————-“);
getch();
}
int stpal(char str[50], int st, int ed)
{
int i,pal=0;
for(i=0;i<=(ed-st)/2;i++)
{
if(str[st+i]==str[ed-i])
pal=1;
else
{
pal=0;
break;
}
}
return pal;
}

Removing spaces and punctuation from a string in C Language


#include<stdio.h>
#include<ctype.h> 

#define BUFFER_LEN 500 /* Length of input buffer */

int main(void)
{
char buffer[BUFFER_LEN]; /* Input buffer */
char *pbuffer1 = buffer; /* Pointer to buffer position */
char *pbuffer2 = buffer; /* Pointer to buffer position */

/* Read a string */
printf("Enter a string of up to %d characters:\n", BUFFER_LEN);
while((*pbuffer1++ = getchar()) != '\n');
*pbuffer1 = ''; /* Append string terminator */
pbuffer1 = buffer; /* Reset pointer to start */
while(*pbuffer1 != '') /* Loop until the end of the string */
{
if(ispunct(*pbuffer1) || isspace(*pbuffer1))
{ /* If it's space or puctuation */
++pbuffer1; /* go to the next character */
continue;
}
else
*pbuffer2++ = *pbuffer1++; /* otherwise, copy the character */
}
*pbuffer2 = ''; /* Append string terminator */
printf("\nWith the spaces and punctuation removed, the string is now:\n%s\n", buffer);
return 0;
}