Below is my final code but no output has been printed in the console. Please help me to find the mistake.
#include<stdio.h>
#include<string.h>
int main()
{
char s[10] = "Gokul";
int len = 0;
while(s[len] != '\0');
len++;
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
if(j==i || j == (len-i-1)){
printf("%c", s[i]);
}
else printf(" ");
}
printf("\n");
}
return 0;
}
while(s[len] != '\0');
len++;
Mistake is here.
The body of your loop is empty
Next time, use a debugger.
The meaning of the statement
while(s[len] != '\0');
is
while (s[len] != '\0') {
}
So in your case the statement
while (s[len] != '\0');
len++;
will be expanded to
while (s[len] != '\0') {
}
len++;
which is wrong based on the logic.
The len++; statement should come inside the while condition.
So either you can use like below
while (s[len] != '\0')
len++;
or
while (s[len] != '\0') {
len++;
}
So I am pasting the working code here
#include<string.h>
int main() {
char s[10] = "Gokul";
int len = 0;
while (s[len] != '\0') {
len++;
}
printf("len=%d\n", len);
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (j == i || j == (len - i - 1)) {
printf("%c", s[i]);
} else printf(" ");
}
printf("\n");
}
return 0;
}
Hope this helps you.
Related
I was trying this pattern matching method in C but whenever I give all the input, the vscode terminal waits for a while and just stops the program without any warnings/message. Can anyone point to what is wrong here?
#include <stdio.h>
#include <string.h>
int main()
{
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, j, k, flag, slP, slR, len;
i = m = k = j = flag = len = 0;
printf("\nMain String: ");
gets(STR);
printf("\nPattern String: ");
gets(PAT);
slP = strlen(PAT);
printf("\nReplace String: ");
gets(REP);
slR = strlen(REP);
while (STR[i] != '\0')
{
if (STR[i] = PAT[j])
{
len = 0;
for (k = 0; k < slP; k++)
{
if (STR[k] = PAT[k])
len++;
}
if (len == slP)
{
flag = 1;
for (k = 0; k < slR; k++, m++)
ANS[m] = REP[k];
}
}
else
{
ANS[m] = STR[i];
m++;
i++;
}
}
if (flag == 0)
{
printf("\nPattern not found!");
}
else
{
ANS[m] = '\0';
printf("\nResultant String: %s\n", ANS);
}
return 0;
}
There are multiple problems in the code:
using gets() is risky, this function was removed from the C Standard because it cannot be used safely.
if (STR[i] = PAT[j]) copied the pattern to the string. You should use:
if (STR[i] == PAT[j])
similarly, if (STR[k] = PAT[k]) is incorrect. You should compare PAT[k] and STR[i + k]:
if (STR[i + k] == PAT[k])
you should test for buffer overflow for the output string as replacing a short string by a larger one may produce a string that will not fit in ANS
you do not increment i properly.
Here is a modified version:
#include <stdio.h>
int getstr(const char *prompt, char *dest, int size) {
int c, len = 0;
printf("%s", prompt);
while ((c = getchar()) != EOF && c != '\n') {
if (len + 1 < size)
dest[len++] = c;
}
if (size > 0)
dest[len] = '\0';
printf("\n");
if (c == EOF && len == 0)
return -1;
else
return len;
}
int main() {
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, k, flag;
if (getstr("Main String: ", STR, sizeof STR) < 0)
return 1;
if (getstr("Pattern String: ", PAT, sizeof PAT) < 0)
return 1;
if (getstr("Replace String: ", REP, sizeof REP) < 0)
return 1;
i = m = flag = 0;
while (STR[i] != '\0') {
if (STR[i] == PAT[0]) { // initial match
// compare the rest of the pattern
for (k = 1; PAT[k] != '\0' && PAT[k] == STR[i + k]; k++)
continue;
if (PAT[k] == '\0') { // complete match
flag = 1;
// copy the replacement string
for (k = 0; REP[k] != '\0'; k++) {
if (m + 1 < sizeof ANS)
ANS[m++] = REP[k];
}
i += k; // skip the matching characters
continue;
}
}
// otherwise copy a single character
if (m + 1 < sizeof ANS)
ANS[m++] = STR[i];
i++;
}
ANS[m] = '\0';
if (flag == 0) {
printf("Pattern not found!\n");
} else {
printf("Resultant String: %s\n", ANS);
}
return 0;
}
Maybe some property is passing unnoticed to me, but when 'i' is 1 it just freeze. When i input whatever string, 'j' variable goes to 700 or 2000 in different executions. The code goal is to output repetitive letters if you input "cheese" the output should be "eee". What am i doing wrong?
#include <stdio.h>
char * repeticoes(char *s) {
int index = 0;
for (int i = 0;( s[i] != '\0'); i++) //problem starts when i is > 0
{
for (int j = 0; ( s[j] != '\0'); j++)
{
if (s[i] == s[j])
{
printf("%c == %c\ni %d j %d\n", s[i], s[j],i,j);
s[index++] = s[i];
}
else
{
printf("not happening %c != %c\ni %d j %d\n", s[i],s[j],i,j);
}
}
}
s[++index] = '\0';
return s;
}
main() {
char input[21];
printf("str 1\n");
fgets(input, 20, stdin);
repeticoes(input);
printf("duplicated letters %s\n", input);
}
You need to start the inner loop at the next character after the one being processed in the outer loop, otherwise you'll process the same pair of characters twice, as well as testing a character against itself when i == j.
You should also break out of the inner loop as soon as you find a match. You'll find later matches in a future iteration of the outer loop. Otherwise you'll process the same pair twice again.
And you shouldn't increment index before assigning the null character after the loop. It was already incremented when adding the repetition.
#include <stdio.h>
char * repeticoes(char *s) {
int index = 0;
for (int i = 0;( s[i] != '\0'); i++) //problem starts when i is > 0
{
for (int j = i+1; ( s[j] != '\0'); j++)
{
if (s[i] == s[j])
{
printf("%c == %c\ni %d j %d\n", s[i], s[j],i,j);
s[index++] = s[i];
break;
}
else
{
printf("not happening %c != %c\ni %d j %d\n", s[i],s[j],i,j);
}
}
}
s[index] = '\0';
return s;
}
int main() {
char input[21];
printf("str 1\n");
fgets(input, 20, stdin);
repeticoes(input);
printf("duplicated letters %s\n", input);
}
With an array of letters to count and an array of counts. Once the letters have been counted, loop through the input again and set the letters that have a count greater than one.
#include <stdio.h>
void repeticoes ( char *s) {
char tocount[] = "abcdefghijklmnopqrstuvwxyz";
size_t len = sizeof tocount;
size_t index = 0;
int count[len];
for (int j = 0; j < len; j++) {
count[j] = 0;
}
for (int i = 0;( s[i] != '\0'); i++) {
for (int j = 0; j < len; j++) {
if ( s[i] == tocount[j]) {
count[j]++;
}
}
}
for (int i = 0;( s[i] != '\0'); i++) {
for (int j = 0; j < len; j++) {
if ( s[i] == tocount[j] && 1 < count[j]) {
s[index] = s[i];
index++;
}
}
}
s[index] = '\0';
}
int main ( void) {
char input[21];
printf("str 1\n");
fgets(input, 20, stdin);
repeticoes(input);
printf("duplicated letters %s\n", input);
return 0;
}
I wrote code that replaces integers from 0 to 3 with strings. I was only allowed to use getchar() and putchar(). If the input is 1, the output will become "one".
#include <stdio.h>
int main()
{
int c;
char* arr[4] = {"zero", "one", "two","three"};
int i;
while ((c = getchar ()) != EOF)
{
if(c==0+'0') {
char* str = arr[0];
for (i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
}
else if(c==1+'0') {
char* str = arr[1];
for (i= 0; str[i] != '\0';i++) {
putchar(str[i]);
}
}
else if(c==2+'0') {
char* str = arr[2];
for (i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
}
else if(c==3+'0') {
char* str = arr[3];
for (i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
}
else
putchar(c);
}
return 0;
}
The code is pretty long. Is there a shorter way to write it?
If I type in 33 the output will be "threethree". Could anyone give me suggestions how can i modify my code not to do that?
note: I am also not allowed to use functions.
You can use a variable to remember last input and compare, so that you will not print continuous char.
#include <stdio.h>
int main()
{
int c;
char* arr[4] = {"zero", "one", "two","three"};
int i;
char last_input = '9';
while ((c = getchar ()) != EOF)
{
if(c != last_input && '0' <= c && c <= '3') {
last_input = c;
int index = c - '0';
char* str = arr[index];
for (i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
}
else{
putchar(c);
}
}
return 0;
}
You can compress your if statements using one if condition like this :
#include <stdio.h>
int main()
{
int c;
char* arr[4] = {"zero", "one", "two","three"};
int i;
while ((c = getchar ()) != EOF) {
int k = c-'0';
if(k>=0 && k<=3) {
char* str = arr[k];
for (i= 0; str[i] != '\0';i++) {
putchar(str[i]);
}
}
else {
putchar(c);
}
}
return 0;
}
Here is the simple approach to the same task. I tried to explain the logic in the comments.
int main(void) {
char *arr[11] = {"zero", "one", "two","three","four","five","six","seven","eight","Nine","Ten"};
int *input = malloc(sizeof(*input))/*1st time 4 byte */ , row = 1;
while( (input[row-1] = getchar())!=EOF ) {
if(input[row-1]==10) /* if ENTER key is presed */
break;
input[row-1] = input[row-1] - 48;/* convert it */
printf("%s ",arr[ input[row-1]%10 ]);/* its simple, just think on it */
row++;
input = realloc(input,row * sizeof(*input));/* reallocate based on number of input */
}
/* free dynamically allocated memory #TODO*/
return 0;
}
I just given hint, make it generic like write the condition if input is less than zero etc. I hope it helps.
Here my code using loop to shorten your code.
#include <stdio.h>
int main()
{
int c;
char* arr[4] = {"zero", "one", "two","three"};
int i, j;
while ((c = getchar ()) != EOF)
{
for(j = 0; j < 4; j++)
{
if(c == j + '0')
{
char* str = arr[j];
for (i = 0; str[i] != '\0'; i++)
{
putchar(str[i]);
}
j = 10; // just to detect processed character
break;
}
}
if(j != 10)
{
putchar(c);
}
}
return 0;
}
My program takes two parameters eg "./a abc xyz" where all a's in a text file are replaced with x's and b's with y's and so on. When given a range, eg. A-C, it reads it as ABC.
The issue I am having is that when I add chars to a certain array(alphaRange2) I get a segmentation fault when I run it. I use the same code for array alphaRange1, which does accept the chars as shown when I print alphaRange1 in a for loop. When I try to print alphaRange2, no values are printed.
Here's my code:
int translate(char set1[], char set2[]) {
int c;
char ch;
char ch2;
int dash1 = 0;
int dash2 = 0;
int previous = -1;
int next;
char alphaRange1[MAXSIZE];
char alphaRange2[MAXSIZE];
size_t i;
int j = 0;
int k;
int l;
for (i=0; i <= strlen(set1); i++) {
if (set1[i] == '-') {
for (ch = set1[i-1]; ch <= set1[i+1]; ch++) {
alphaRange1[k] = ch;
k++;
}
}
}
for (i=0; i <= strlen(set2); i++) {
if (set2[i] == '-') {
for (ch = set2[i-1]; ch <= set2[i+1]; ch++) {
alphaRange2[l] = ch;
l++;
}
}
}
/*for (i=0; alphaRange1[i] != '\0'; i++) {
printf("%c", alphaRange1[i]);
}*/
while ((c = getchar()) != EOF) {
if ((dash1 == 1) && (dash2 == 1)) {
for (i=0; alphaRange1[i] != '\0' || alphaRange2[i] != '\0'; i++) {
if (c == alphaRange1[i]) {
c = alphaRange2[i];
}
}
} else if ((dash1 == 0) && (dash2 == 0)) {
for (i=0; i <= strlen(set1) || i <= strlen(set2); i++) {
if (c == set1[i]) {
c = set2[i];
if ((c == set1[1]) && (set1[1] == set2[0])) {
c = set2[0];
break;
}
}
}
}
if (previous > -1) {
putchar(previous);
}
previous = c;
}
putchar('\n');
return 1;
}
int main(int argc, char *argv[]) {
int i, j, k;
char set1[MAXSIZE];
char set2[MAXSIZE];
char ch;
char alphaRange1[MAXSIZE];
for (i=0; i < argc; i++) {
for (j=0; argv[1][j] != '\0' || argv[2][j] != '\0'; j++) {
set1[i] = argv[1][i];
set2[i] = argv[2][i];
}
}
/*for (i=0; i <= strlen(set1); i++) {
if (set1[i] == '-') {
for (ch = set1[i-1]; ch <= set1[i+1]; ch++) {
alphaRange1[k] = ch;
k++;
}
}
}
for (i=0; alphaRange1[i] != '\0'; i++) {
printf("%c", alphaRange1[i]);
}*/
translate(set1, set2);
return 1;
}
The code runs if you take out anything including alphaRange2, and I've been testing it using commented out print loop, which works if you comment out the entire while loop. How do I make this work?
Thanks.
I wrote a program to fill in closed figures with asterisks.
For some reason it isn't accepting the sentinel value EOF Ctrl+D.
Why is this?
#include "usefunc.h"
#define height 100
#define width 100
void showRow(int numbers[], int size_numbers) {
int i;
printf("[ ");
for (i = 0; i < size_numbers-3; i++) {
printf("%c, ", numbers[i]);
}
printf("%c ]", numbers[size_numbers-3]);
printf("\n");
}
void showshape(int shape[][width], int lines, int max_buf) {
int i, j;
for (i = 0; i < lines; i++) {
for (j = 0; j < max_buf; j++) {
printf("%c", shape[i][j]);
}
printf("\n");
}
}
void fill(int row[][width], int rownum, int end) {
int i, c = 1, inside = 0;
for (i = 0; i < end; i++) {
if (row[rownum][i] == '*') {
c++;
}
if (!(c%2)) inside = 1;
else inside = 0;
if (inside) {
row[rownum][i] = '*';
}
}
}
int main () {
int shape[height][width], i = 0, j = 0, lines = 0;
int sentinel = 0;
int temp = 0;
while (sentinel != EOF) {
while ((temp = getchar()) != '\n') {
sentinel = temp;
shape[i][j] = temp;
j++;
}
i++;
lines++;
}
for (i = 0; i < lines; i++) {
fill(shape, i, width);
}
fill(shape, 0, j);
//for (i = 0; i < lines; i++)
showshape(shape, lines, j+2);
}
Edit 1
Just updated the code. It doesn't quite print the box. what's going on?
Edit 2
Another update. This time I'm copying the value of temp, however I get
Bus error
What am i doing wrong?
You want:
int temp;
EOF is an integer value, not a char.
while ((temp = getchar()) != '\n') {
shape`[i][j]` = temp;
j++;
}
I suspect this this never exits once EOF is reached. I mean, getchar probably continues to throw EOF at you and you ask "Not \n ? Okay, no need to stop".
Also, what #Neil Butterworth said in his answer is really sensible.