I have been trying to reverse(and print it that way) a given string only using for loops and nothing more. I think I have built up the basic logic, but it has some defects. When run, it only reverses the first two characters and then stops. Please help me find the defect in my logic.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
for(i=1;i>=0;i--)
{
printf("%c",a[i]);
}
}
For starters the function gets is not a standard C function any more. it is unsafe. Instead use the standard C function fgets. The function can append the new line character '\n' to the entered string that should be excluded from the string.
It is unclear from your question whether you are allowed to use standard string functions.
Nevertheless here is a demonstrative program that does the task without using standard C string functions and that uses only for loops (neither while loop nor do-while loop).
#include <stdio.h>
int main(void)
{
enum { N = 20 };
char s[N];
printf( "Enter any String less than %d symbols: ", N );
fgets( s, N, stdin );
// remove the new line character and calculate the length of the string
size_t n = 0;
for ( ; s[n] != '\0' && s[n] != '\n'; ) ++n;
s[n] = '\0';
// reverse the string
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
puts( s );
return 0;
}
Its output might look the following way
Enter any String less than 20 symbols: Hello dev.aniruddha
ahddurina.ved olleH
If you want just to output the original string in the reverse order then the program can look like
#include <stdio.h>
int main(void)
{
enum { N = 20 };
char s[N];
printf( "Enter any String less than %d symbols: ", N );
fgets( s, N, stdin );
// remove the new line character and calculate the length of the string
size_t n = 0;
for ( ; s[n] != '\0' && s[n] != '\n'; ) ++n;
s[n] = '\0';
// reverse the string
for ( ; n-- != 0; )
{
putchar( s[n] );
}
putchar( '\n' );
return 0;
}
Its output is the same as shown above
Enter any String less than 20 symbols: Hello dev.aniruddha
ahddurina.ved olleH
gets() is a bad idea as you can easily get overflows and it is no longer part of the c standard.
So let's assume that the string entered fits the array and this is just for an excercise with no reallife usage.
Your first loop finds the terminator. That's good.
Your second loop sets the variable that indicates the terminator to 1, destroying the result.
If you remove the assignment i=1, your program compiles with gcc and does what you want.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
for(;i>=0;i--) //removed i=1 here
{
printf("%c",a[i]);
}
}
But there are still some issues to be addressed.
You will also reverse the terminator, instead you should start from i-1
I would advise to not use a for loop if you do not have a counter criterion The first loop should rather be a while loop, but as it was part of the assignment you had no choice still I will replace it in my recommendation. As they can easily be swapped.
Then you could use another variable for the second loop for clarity.
Also NULL is the NULL-pointer not the value 0 (also namend NUL apperantly) . So you should replace this either with 0 or with '\0'
Also stdlib.h is not required here
#include<stdio.h>
int main()
{
char a[20];
int i = 0;
printf("Enter any String\n");
gets(a);
while (a[i] != 0)
{
i++;
}
for(int j = i-1; j>=0; j--) // -1 to get the value in front of the terminator
{
printf("%c",a[j]);
}
printf("\n"); //to flush the output.
}
Here is the solution code.
The first for loop is to be used for determining the length of the string and the second for loop is for traversing the string from the last position to the first.
#include<stdio.h>
int main()
{
char a[20];
int i,j,len;
printf("Enter a String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
len=i;
for(j=len-1;j>=0;j--)
{
printf("%c",a[j]);
}
}
I think why only two chars are been return is because of the condition statement in your second "for loop".
for(i=1;i>=0;i--)
Note:
it repeats from 1~0 (1,0): meaning it will repeat only twice
first iteration: when i == 1
second iteration: when i == 0 ; then it ends .
Please note that you created two "for loops" with the first one having no content.
Bonus:
I tried to fixed your code but realized that my C language skills isnt the best lol . Anyways, i came up with something that you could reference but it only reverse strings of less than 8 elements.
#include<stdio.h>
#include<stdlib.h>
int findlength(char a[]);
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
int len = findlength(a);
printf("Lenght of the String is: %d \n",len);
printf("Reversed String is: ");
for(i=len;i>-1;i--){
printf("%c",a[i]);
}
}
int findlength(char a[]){
int result = 0;
int i;
for(i=0;i<sizeof(a) / sizeof(char);i++){ // sizeof(char) is 1
if(a[i] == '\0') //end of string
return result;
result += 1;
}
return result;
}
Related
Can someone help me with my code. I have to create a program, where the user puts in a word and that word has to be given out backwards.
My code doesn't really work, because the backward word puts out some random characters and then gives out the right word.
#include <stdio.h>
int main(){
char word[10];
printf("Please enter a word : ");
scanf("%s", word);
for (int i = 10; i >= 0; i--){
if (word[i] !=0){
printf("%c", word[i]);
}
}
return 0;
}
For starters this call of scanf
scanf("%s", word);
is unsafe. You need at least to specify the length of the entered string like
scanf("%9s", word);
The second problem is that the user can enter less than 9 characters. So this for loop
for (int i = 10; i >= 0; i--){
is incorrect. And moreover the index equal to 10 points to memory outside the array. So this if statement
if (word[i] !=0){
in any case wrong when i is equal to 10.
You need to find the length of the entered string.
The program can look the following way
#include <stdio.h>
#include <string.h>
int main( void )
{
char word[10];
printf( "Please enter a word : " );
if ( scanf( "%9s", word ) == 1 )
{
for ( size_t n = strlen( word ); n != 0; --n )
{
putchar( word[n-1] );
}
putchar( '\n' );
}
}
You're accessing outside the array, since your loop starts at i=10, but the last element of the array is word[9]. And if the user types less than 9 characters, you'll print uninitialized characters.
Use strlen() to determine how long the word is. Then subtract 1 from this to get the index of the last character.
for (int i = strlen(word)-1; i >= 0; i--)
You should also print a newline at the end.
This is one of the assignments for my class and this is the objective of the assignment:
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. You may assume that the string does not contain spaces and will always contain less than 50 characters.
This is the code I have so far and I am new to C programming so I don't know how to declare Strings correctly just yet. So far I learned there are no strings in C like there is in Java and you have to do them as a character array:
#include <stdio.h>
#include <string.h>
int main(void) {
char userChar;
char userString[50];
int count = 0;
for (int i = 0; i < userChar; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d", count);
if (count != 1)
printf("'s");
return 0;
}
For example, if I wanted to input n Monday and output 1 n
What would I need to change in my code to go from n Monday to 1 n
This is the only output I am getting, and it only has outputted one thing correctly:
0's
First, I hope this is not considered cheating :-)
Second, you need to define userChar and userString as arguments for main, and pass them in at run time. They are assigned nothing, so that is why you get
0's
Third, your for condition is wrong. You need this so it only iterates through the length of the string:
for (int i = 0; i < strlen(userString); i++)
Finally, You are not printing the value of userChar prior to the return
At first you need to input a string and a character. To count the number of occurrences of the character in the string you can use standard string function strchr.
The program can look something like the following
#include <stdio.h>
#include <string.h>
int main(void)
{
char userChar = ' ';
char userString[50] = "";
printf( "Enter a string without embedded spaces\nof the length less than %d: ", 50 );
scanf( "%49s", userString );
printf( "Enter a character to search in the string: " );
scanf( " %c", &userChar );
size_t n = 0;
for ( const char *p = userString; ( p = strchr( p, userChar ) ) != NULL; ++p )
{
++n;
}
printf( "%zu%s %c\n", n, n < 2 ? "" : "'s", userChar );
}
The expected output is not 0's, it should include the counted character: for example if the character is n and the string Monday, the output should be
1 n
and if the string is Eeny-meeny-miny-moe, the output would be
3 n's
Here is a modified version:
#include <stdio.h>
int main() {
char userChar;
char userString[50];
int i, count;
printf("Enter character: ");
scanf(" %c", &userChar);
printf("Enter string (single word): ");
// read a word with at most 49 characters
scanf(" %49s", userString);
count = 0;
for (i = 0; userString[i] != '\0'; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d %c", count, userChar);
if (count != 1)
printf("'s");
printf("\n");
return 0;
}
This is a word guessing game. For example, hello is given as h___o and the user must guess the letters.
I set a condition on my loop but don't know why it is not breaking the while loop.
#include <stdio.h>
#include <string.h>
int main()
{
char word[] = "hello";
int length = strlen(word);
int check;
char spaceLetters[length];
int i, j;
spaceLetters[0] = word[0];
char *dash = "_";
for (i = 1; i < length; i++)
{
strncat(spaceLetters, dash, 1);
}
int attemptLeft = length;
printf("\n %s\n", spaceLetters);
printf("\t\t\tAttempt Left: %d\n", attemptLeft);
boolean start = T;
int userInput;
while (1)
{
printf("\n");
printf("Enter Letter:");
scanf("%c", &userInput);
for loop for checking entered letter is true or not
for (j = 1; j < length;j++)
{
if (word[j] == userInput)
{
spaceLetters[j] = word[j];
printf("%s\n", spaceLetters);
printf("\t\t\tAttempt Left: %d\n", attemptLeft);
printf("\n");
}
}
this is my break loop condition when hello == hello break loop
if(word == spaceLetters){
break;
}
}
}
Strings are represented by arrays/pointers. They need to be compared using string library. Replace
if ( word == spaceLetters )
with
if ( strcmp ( word, spaceLetters ) == 0 )
You'll also need to add #include <string.h>.
For starters instead of this call
scanf("%c", &userInput);
^^^
you have to use this call
char userInput;
//...
scanf(" %c", &userInput);
^^^^
Otherwise the call will read also white spaces as the new line character '\n' that is stored in the input buffer after pressing the Enter key by the user.
Arrays do not have the comparison operator ==. You have to compare arrays element by element. To compare strings stored in character arrays you should use the standard function strcmp
#include <string.h>
//...
if( strcmp( word, spaceLetters ) == 0 ){
break;
}
But before using this function the array specialLetters must be declared like
char spaceLetters[sizeof( word )] = ""`;
That is the array shall contain a string.
Otherwise this for loop in your program invokes undefined behavior.
for (i = 1; i < length; i++)
{
strncat(spaceLetters, dash, 1);
}
And it does not make a great sense.
You could just write
char dash = '_';
memset( spaceLetters + 1, dash, sizeof( spaceLetters ) - 2 );
I am trying to make a program which takes in a input of "Hello" and outputs "olleH" from reversing the order of the characters. However I keep getting a segmentation fault and I don't understand why
#include <stdio.h>
#include<string.h>
int main()
{
int i;
int size;
char s[100],a[100];
printf("Enter the word you want to get reversed: ");
scanf("%s",s);
while(s[i]!='\0')
{
a[i]=s[i];
i++;
}
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
printf("The reversed string is : %s",s);
}
Another simple way to reverse string.
Try this:
while(s[++i]!='\0'); // find the size of string
while(i>=0)
a[j++] = s[--i]; // reverse the string
a[j]='\0';
printf("The reversed string is : %s",a);
This while loop
while(i<sizeof(s))
{
s[i]=a[size];
}
does not make sense because index i has a value that points to outside the entered string (provided that it was initially correctly initialized) and the loop is infinite because i is not changed (and was not initially initialized) in the loop and also the right hand expression of this statement
s[i]=a[size];
is always the same and again refers memory outside the array.
Take into account that neither function declared in <string.h> is used in the program. So the header may be removed.
The program can look the following way
#include <stdio.h>
#define N 100
int main()
{
char s[N], d[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
for ( size_t i = 0; i != n; i++ ) d[i] = s[n-i-1];
d[n] = '\0';
printf( "The reversed string is : %s\n", d );
return 0;
}
You can reverse a string without using an auxiliary array. For example
#include <stdio.h>
#define N 100
int main()
{
char s[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
s[n] = '\0';
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
printf( "The reversed string is : %s\n", s );
return 0;
}
The problem is in this part:
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
sizeof(s) will be 100 whereas the string you read from input can be less than that -- which would be undefined if you access uninitialized parts of s. So, you want to use strlen() to get the actual size of the string and use it to reverse.
Notice that scanf() is unsafe as it's written (what if you input more than 100 chars?). Suggest using fgets() instead.
I'm writing a program to check whether a string is palindrome or not using recursion.Palindrome string is the one that can be read backwards just the same as reading it forward. However following is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
printf("Enter the number of characters in your string\n");
scanf("%d",&num);
char string[num];
char string2[num];
int i;
printf("Enter your string\n");
for (i=0;i<num;i++)
{
scanf("%c",&string[i]);
}
fillString(string,string2,num);
int palin = isPalind(string,string2,num);
if (palin) printf("The string you entered is palindrome");
else printf("The string you entered is not palindrome");
return 0;
}
int isPalind(char string[],char string2[],int num)
{
int i=0;
while (i<num)
{
if (string[i]!=string2[i])
{
i++;
return 0;
}
else{
i++;
return 1*isPalind(string,string2,num);
}
}
}
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<num;i++)
string2[i-1]=string[num-i];
}
I have a logical error, the program compiles fine and executes but it always gives out "The string is not palindrome"
In the fillString the loop is iterating num-1 times (i is from 1 to num-1), so not the whole string is copied. The first character of the original string is omitted. You should do
for (i=1;i<=num;i++) ...
As for the recursive function, it is not really recursive. In recursive call modified input should be passed, but in your case exactly the same input is passed. So in case of true palindrome, it's likely you will get stack overflow due to non-termination. I would propose another approach, to work with single string recursively:
1) Base case: String is a palindrome if of length 0 or 1
2) Recursion step: String is a palindrome if the first character equals to the last and the string without first and last characters is palindrome.
Is your fillString() function reversing your string as expected? It looks like the first letter of string1 is not getting added into the last position of string2 because the for loop stops when i < num fails. Try switching it to i <= num and seeing if that helps.
Double-check this example:
Given: String1 = "Hello". String2 = null for now. num = 5.
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<num;i++)
string2[i-1]=string[num-i];
}
When i = 4, you have string2 = 'olle'. When i = 5, the for loop condition fails, so it doesn't populate string2[4] = 'H'.
updated:
void fillString(char string[],char string2[],int num)
{
int i;
for (i=1;i<=num;i++)
string2[i-1]=string[num-i];
}
The both functions are wrong. They can be written the following way
int isPalind( const char string[], const char string2[], int num )
{
return ( num == 0 ) ||
( string[0] == string[--num] && isPalind( string + 1, string2, num ) );
}
void fillString( const char string[], char string2[], int num )
{
int i;
for ( i = 0; i < num; i++ ) string2[i] = string[num-i-1];
}
If you need not necessary a recursive function then you could use simply standard function memcmp that to determine whether two strings are equal.