Prefix to Infix with minimum number of parenthesis using c language - c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stack
{
char stk[50][50];
int top;
};
typedef struct Stack stack;
void push(stack *p, char c)
{
p->top++;
p->stk[p->top][0] = c ;
p->stk[p->top][1] = '\0';
}
void puush(stack *p, char val[])
{
p->top++;
int i=0 , len = strlen(val);
for( i = 0; i< len ; i++)
p->stk[p->top][i] = val[i];
p->stk[p->top][i] = '\0';
}
void pop(stack *p)
{
p->top--;
}
char *top(stack *p)
{
return p->stk[p->top];
}
void print(stack *p)
{
int i = 0;
while(i <= p->top)
{
printf("index : %d elements : %s\n", i+1, p->stk[i]);
i++;
}
printf("\n");
}
int isOperand(char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return 1;
else return 0;
}
int isOperator(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
return 1;
default:
return 0;
}
}
void prefixToInfix(char s[])
{
stack s1;
s1.top = -1;
int i=0, len = strlen(s) - 1;
for(i = len ; i>= 0 ; i--)
{
if(isOperand(s[i]))
{
printf("%c\n\n",s[i]);
push(&s1, s[i]);
print(&s1);
}
if(isOperator(s[i]))
{
char concat[20];
int k,j= -1;
concat[++j] = '(';
char *c1 = top(&s1);
pop(&s1);
int len1 = 0;
len1 = strlen(c1);
for(k=0; k<len1; k++)
{
concat[++j] = c1[k];
}
concat[++j] = s[i];
c1 = top(&s1);
len1 = strlen(c1);
pop(&s1);
for(k= 0; k<len1; k++)
concat[++j] = c1[k];
concat[++j]=')';
concat[++j] = '\0';
printf("gnerated %s\n",concat);
puush(&s1, concat);
print(&s1);
}
}
printf("%s",top(&s1));
}
int main()
{
prefixToInfix("*-A/BC-/AKL");
}
Please help me, I am not getting the correct output as it should be. I am sharing my code thus it will be easier for you all to understand the problem of my Code
Explanation of my problem:
I have been trying to write a code which converts The Prefix form to Infix. I am getting the output as I expected except one extra parenthesis at last:
For example:
The Input: "*-A/BC-/AKL"
Expected Output: ((A-(B/C))*((A/K)-L)
However my Program output:
((A-(B/C))*((A/K)-L)(, the last extra parenthesis is the issue "("

Related

Allocated Dynamically Array of pointers

i'm really stuck.
I pust a big part of code you can try to run it on in online c compiler. My problem is weird, every time after 2 iteration i lost the data on spliter[0][0] when i mean "lost" is modified, for better understand please look what is printing it.
Inside
Inside the loop that iterates I wanted to see if the characters were well allocated in the present time and this is the case, only afterwards when I want to check it is impossible for me to do anything.
My program boils down to separating one character string according to another and dynamically allocating these character strings in my split. Each separator character counts as separator.
I have already prepared the test in comment. I really need help, too long time im stuck here..
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int is_c(char c, char *cha) {
while (*cha) {
if (*cha == c) {
return (1);
}
cha++;
}
return (0);
}
int ct_str(char *str, char *cha) {
int sw;
int nbr;
char item;
nbr = 0;
while (*str) {
if (!(is_c(*str, cha)) && *str >= 33 && *str <= 127 && sw == 1) {
sw = 0;
nbr+=1;
}
str++;
while (is_c(*str, cha)) {
str++;
sw = 1;
}
}
return (nbr);
}
int no_blk(char *str, int position, char *cha) {
while (!is_c(str[position], cha)) {
if (str[position] >= 33 && str[position] <= 127)
return (1);
position++;
}
return (0);
}
int get_size(char *str, int position, char *cha) {
int item;
item = position;
int j;
j = 0;
while (str[item]) {
if (is_c(str[item], cha))
return (j);
item++;
j++;
}
return (0);
}
void split_this(char **split, char *str, char *cha) {
int i;
int level;
int sw;
int e;
level = 0;
i = 0;
int item = 0;
int element = 0;
while(str[i + 1]) {
e = 0;
while(is_c(str[i], cha)) {
sw = 1;
i++;
}
if(sw == 1 && (!is_c(str[i], cha)) && no_blk(str, i, cha)) {
split[level] = (char*)malloc(sizeof(char) * get_size(str, i, cha) + 1);
e = i;
//printf("%i \n", get_size(str, i, cha));
while(e - i < get_size(str, i, cha)) {
split[level][e - i] = str[e];
//printf("%c", split[level][e - i]);
split[level][(e + 1) - i] = '\0';
e++;
}
printf("%c", split[0][0]);
sw = 0;
level++;
}
i++;
}
free(split);
/*
int it = 0;
int ee;
while(split[it]) {
ee = 0;
while(split[it][ee]) {
printf("%c", split[it][ee]);
ee++;
}
it++;
}
*/
}
void ft_split(char *str, char *cha) {
char **spliter = NULL;
spliter = (char**)malloc(sizeof(char) * ct_str(str, cha) + 1);
split_this(spliter, str, cha);
}
int main(int argc, char **argv) {
//if (argc == 3)
//ft_split(argv[1], argv[2]);
ft_split("%%am%s%s%ss%%s%%%qsdqsd%%%on%vs%lre%" , "%%");
return (0);
}

why a newline is being created in the below function?

I tried to create an own printf function only for printing double, int and character value, here goes the code
#include<stdarg.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
void inta(int ch) {
int count = 0;
int num = ch;
while (ch != 0) {
ch /= 10;
count++;
}
int t = 0;
char *s = (char*) calloc((count + 1), (sizeof(char)));
printf("%s\n", s);
while (num > 0) {
s[t] = 48 + (num % 10);
num /= 10;
t++;
}
s[t] = '\0';
int len = t - 1;
for (int a = 0; a < t / 2; a++) {
char temp = s[a];
s[a] = s[len];
s[len] = temp;
len--;
}
for (int a = 0; a < t; a++) {
putch(s[a]);
}
}
void floata(double num) {
int n = (int) num;
inta(n);
double rem = num - n;
//printf("rem = %lf\n",rem);
while (1) {
if (rem - (int) rem < 0.0001) {
break;
} else {
rem *= 10;
// printf("rem npw %lf\n",rem);
}
}
putch('.');
inta(rem);
}
void chara(int ch) {
putch(ch);
}
void print(const char *str, ...) {
float p;
int ch;
va_list ap;
va_start(ap, str);
char *fmt;
for (fmt = str; *fmt != '\0'; fmt++) {
while (*fmt != '%') {
putch(*fmt);
fmt++;
}
fmt++;
switch (*fmt) {
case 'c':
ch = va_arg(ap, int);
chara(ch);
break;
case 'd':
ch = va_arg(ap, int);
if (ch < 0) {
putch('-');
ch = -ch;
}
inta(ch);
break;
case 'f':
p = va_arg(ap, double);
if (p < 0) {
putch('-');
p = -p;
}
floata(p);
break;
}
}
va_end(ap);
}
int main() {
int q = 119;
double aa = 12.34;
int a = 123;
char b = 'z';
print("%d %f %c", q, aa, b);
}
The expected output should be:
123 12.34 z
but the output is:
119
12.
34 z
I used putch function to print every character, why some newlines is being created?
How to remove this newline>?
How to remove this newline>?
Remove printf("%s\n", s);

why Segmentation fault: 11 occurred for my C code?

I tried to write a function that deletes each character in string s1 that matches any character in the string s2.
Here is the testing code for the squeeze method.
#include <stdio.h>
void squeeze(char s1[], char s2[]);
int main()
{
char s1[20] = "HelloWorld", s2[20] = "ol";
squeeze(s1, s2);
printf("%s\n", s1);
return 0;
}
void squeeze(char s1[], char s2[])
{
int i, j, k;
k = 0;
for (i = 0; s1[i] != '\0'; ++i) {
for (j = 0; s2[j] != '\0'; ++j) {
if (s1[i] != s2[j])
s1[k++] = s1[i];
}
}
s1[k] = '\0';
}
When I run this code, terminal always gives Segmentation fault: 11.
Could anyone please give me any hints why this happens?
Example:
#include <stdio.h>
static int found(char *str, char c) { // return 1 if c is found in str
for (size_t i = 0; str[i] != '\0'; i++) {
if (str[i] == c) {
return 1;
}
}
return 0;
}
static void squeeze(char *a, char *b) {
size_t k = 0;
for (size_t i = 0; a[i] != '\0'; i++) { // use size_t to iterate on a c-string
if (found(b, a[i]) != 1) {
a[k++] = a[i]; // copy only if a[i] is not in b
}
}
a[k] = '\0';
}
int main(void) {
char a[] = "HelloWorld"; // you should let auto size
char b[] = "ol"; // and separate declaration
squeeze(a, b);
printf("%s\n", a);
}
Problem with your code is s1[k++] = s1[i];
Try to use new array
See Following Code
#include<stdio.h>
char *squeeze(char s1[], char s2[]);
int main()
{
char s1[20] = "HelloWorld", s2[20] = "olH";
squeeze(s1, s2);
return 0;
}
char *squeeze(char s1[], char s2[])
{
int i, j, k;
k = 0;
char arr[100]; // new array
int flag = 0;
for (i = 0; s1[i] != '\0'; i++) {
flag = 0;
for (j = 0; s2[j] != '\0'; ++j) {
if (s1[i] == s2[j])
{
flag = 1;
break;
}
}
if (flag == 0)
{
arr[k++] = s1[i];
}
}
arr[k] = '\0';
printf("%s",arr);
}

C - recursive permutations in lexicographical order

I am trying to make permutations of strings with up to 8 characters. The problem is it must be done with recursion and it must be in lexicographical order. I found one solution with the recursion but it only works for 4 characters max. After that, it starts to mess up again.
void swap(char* a, char* b){
char temp = *a;
*a = *b;
*b = temp;
}
void recursion(char* arr, int start, int n){
if (start == (n-1)){
printf("%s\n", arr);
return;
}
for (int i = start; i < n; i++){
recursion(arr, start+1, n);
swap(arr+start+1, arr+n-1);
int j = start+1;
while (j < n && arr[start] > arr[j]){
j++;
}
if (j >= n){
continue;
}
swap(arr+start, arr+j);
}
swap(arr+start+1, arr+n-1);
}
int main(int argc, char *argv[]) {
char arr[9];
char charakter;
int m = 0;
while (scanf("%c", &charakter) != EOF){
if (charakter == '\n'){
break;
}
else if (isalpha(charakter) || isdigit(charakter)){
arr[m] = charakter;
m++;
}
else{
fprintf(stderr, "Error!\n");
return 100;
}
}
arr[m] = '\0';
int n = strlen(arr);
int start = 0;
recursion(arr, start, n);
return 0;
}
Any idea how to fix the recursion function?
Your solution is strange, have a look here and here a fix:
void recursion(char *arr, int start, int n) {
if (start == n) {
printf("%s\n", arr);
return;
}
for (int i = start; i < n; i++) {
swap(arr + start, arr + i);
recursion(arr, start + 1, n);
swap(arr + start, arr + i);
}
}
here a proper solution:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
static void recursion(char *str, size_t n, size_t max) {
if (n < max) {
recursion(str, n + 1, max);
for (size_t i = n + 1; i < max; i++) {
char tmp = str[i];
str[i] = str[n];
str[n] = tmp;
recursion(str, n + 1, max);
str[n] = str[i];
str[i] = tmp;
}
} else {
printf("%s\n", str);
}
}
int main(void) {
char str[42];
errno = 0;
if (scanf("%41s", str) != 1) {
if (errno != 0) {
perror("scanf()");
} else {
fprintf(stderr, "no input");
}
return 1;
}
recursion(str, 0, strlen(str));
}

Count the number of occurrences of each letter in string

How can I count the number of occurrences in c of each letter (ignoring case) in the string? So that it would print out letter: # number of occurences, I have code to count the occurences of one letter, but how can I count the occurence of each letter in the string?
{
char
int count = 0;
int i;
//int length = strlen(string);
for (i = 0; i < 20; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
output:
a : 1
b : 0
c : 2
etc...
Let's assume you have a system where char is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
if ( count[i] != 0) {
printf("The %c. character has %d occurrences.\n", i, counts[i]);
}
}
Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
Like this:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
This code assumes that the string is null-terminated, and that it contains only characters a through z or A through Z, inclusive.
To understand how this works, recall that after conversion tolower each letter has a code between a and z, and that the codes are consecutive. As the result, tolower(*p) - 'a' evaluates to a number from 0 to 25, inclusive, representing the letter's sequential number in the alphabet.
This code combines ++ and *p to shorten the program.
One simple possibility would be to make an array of 26 ints, each is a count for a letter a-z:
int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc
Then loop through the string and increment the count for each letter:
for(int i = 0; i<strlen(mystring); i++) //for the whole length of the string
if(isalpha(mystring[i]))
alphacount[tolower(mystring[i])-'a']++; //make the letter lower case (if it's not)
//then use it as an offset into the array
//and increment
It's a simple idea that works for A-Z, a-z. If you want to separate by capitals you just need to make the count 52 instead and subtract the correct ASCII offset
#include <stdio.h>
#include <string.h>
void main()
{
printf("PLEASE ENTER A STRING\n");
printf("GIVE ONLY ONE SPACE BETWEEN WORDS\n");
printf("PRESS ENETR WHEN FINISHED\n");
char str[100];
int arr[26]={0};
char ch;
int i;
gets(str);
int n=strlen(str);
for(i=0;i<n;i++)
{
ch=tolower(str[i]);
if(ch>=97 && ch<=122)
{
arr[ch-97]++;
}
}
for(i=97;i<=122;i++)
printf("%c OCCURS %d NUMBER OF TIMES\n",i,arr[i-97]);
return 0;
}
After Accept Answer
A method that meets these specs: (IMO, the other answers do not meet all)
It is practical/efficient when char has a wide range. Example: CHAR_BIT is 16 or 32, so no use of bool Used[1 << CHAR_BIT];
Works for very long strings (use size_t rather than int).
Does not rely on ASCII. ( Use Upper[] )
Defined behavior when a char < 0. is...() functions are defined for EOF and unsigned char
static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
void LetterOccurrences(size_t *Count, const char *s) {
memset(Count, 0, sizeof *Count * 26);
while (*s) {
unsigned char ch = *s;
if (isalpha(ch)) {
const char *caseset = Upper;
char *p = strchr(caseset, ch);
if (p == NULL) {
caseset = Lower;
p = strchr(caseset, ch);
}
if (p != NULL) {
Count[p - caseset]++;
}
}
}
}
// sample usage
char *s = foo();
size_t Count[26];
LetterOccurrences(Count, s);
for (int i=0; i<26; i++)
printf("%c : %zu\n", Upper[i], Count[i]);
}
You can use the following code.
main()
{
int i = 0,j=0,count[26]={0};
char ch = 97;
char string[100]="Hello how are you buddy ?";
for (i = 0; i < 100; i++)
{
for(j=0;j<26;j++)
{
if (tolower(string[i]) == (ch+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",97+j,count[j]);
}
}
Hope this helps.
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
for (int i=0;i<word.length();i++){
int counter=0;
for (int j=0;j<word.length();j++){
if(word.charAt(i)==word.charAt(j))
counter++;
}// inner for
JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
}// outer for
#include<stdio.h>
void frequency_counter(char* str)
{
int count[256] = {0}; //partial initialization
int i;
for(i=0;str[i];i++)
count[str[i]]++;
for(i=0;str[i];i++) {
if(count[str[i]]) {
printf("%c %d \n",str[i],count[str[i]]);
count[str[i]]=0;
}
}
}
void main()
{
char str[] = "The quick brown fox jumped over the lazy dog.";
frequency_counter(str);
}
Here is the C code with User Defined Function:
/* C Program to count the frequency of characters in a given String */
#include <stdio.h>
#include <string.h>
const char letters[] = "abcdefghijklmnopqrstuvwxzy";
void find_frequency(const char *string, int *count);
int main() {
char string[100];
int count[26] = { 0 };
int i;
printf("Input a string: ");
if (!fgets(string, sizeof string, stdin))
return 1;
find_frequency(string, count);
printf("Character Counts\n");
for (i = 0; i < 26; i++) {
printf("%c\t%d\n", letters[i], count[i]);
}
return 0;
}
void find_frequency(const char *string, int *count) {
int i;
for (i = 0; string[i] != '\0'; i++) {
p = strchr(letters, string[i]);
if (p != NULL) {
count[p - letters]++;
}
}
}
Have checked that many of the answered are with static array, what if suppose I have special character in the string and want a solution with dynamic concept. There can be many other possible solutions, it is one of them.
here is the solutions with the Linked List.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node {
char data;
int counter;
struct Node* next;
};
void printLinkList(struct Node* head)
{
while (head != NULL) {
printf("\n%c occur %d", head->data, head->counter);
head = head->next;
}
}
int main(void) {
char *str = "!count all the occurances of character in string!";
int i = 0;
char tempChar;
struct Node* head = NULL;
struct Node* node = NULL;
struct Node* first = NULL;
for(i = 0; i < strlen(str); i++)
{
tempChar = str[i];
head = first;
if(head == NULL)
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
if(first == NULL)
{
first = node;
}
}
else
{
while (head->next != NULL) {
if(head->data == tempChar)
{
head->counter = head->counter + 1;
break;
}
head = head->next;
}
if(head->next == NULL)
{
if(head->data == tempChar)
{
head->counter = head->counter + 1;
}
else
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
head->next = node;
}
}
}
}
printLinkList(first);
return 0;
}
int charset[256] = {0};
int charcount[256] = {0};
for (i = 0; i < 20; i++)
{
for(int c = 0; c < 256; c++)
{
if(string[i] == charset[c])
{
charcount[c]++;
}
}
}
charcount will store the occurence of any character in the string.
//This is JavaScript Code.
function countWordOccurences()
{
// You can use array of words or a sentence split with space.
var sentence = "The quick brown fox jumped over the lazy dog.";
//var sentenceArray = ['asdf', 'asdf', 'sfd', 'qwr', 'qwr'];
var sentenceArray = sentence.split(' ', 1000);
var output;
var temp;
for(var i = 0; i < sentenceArray.length; i++) {
var k = 1;
for(var j = i + 1; j < sentenceArray.length; j++) {
if(sentenceArray[i] == sentenceArray[j])
k = k + 1;
}
if(k > 1) {
i = i + 1;
output = output + ',' + k + ',' + k;
}
else
output = output + ',' + k;
}
alert(sentenceArray + '\n' + output.slice(10).split(',', 500));
}
You can see it live --> http://jsfiddle.net/rammipr/ahq8nxpf/
//c code for count the occurence of each character in a string.
void main()
{
int i,j; int c[26],count=0; char a[]="shahid";
clrscr();
for(i=0;i<26;i++)
{
count=0;
for(j=0;j<strlen(a);j++)
{
if(a[j]==97+i)
{
count++;
}
}
c[i]=count;
}
for(i=0;i<26;i++)
{
j=97+i;
if(c[i]!=0) { printf("%c of %d times\n",j,c[i]);
}
}
getch();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var FullName = "stackoverflow"
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
// Label1.Text=item.Value + " " + item.Key + "<br />";
spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
}
}

Resources