How to give out a word backwards in c - c

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.

Related

My program prints more than 1 sentence, want it to print only one sentence

I have a problem with my program
The first problem is if I feed in the sentence containing more than 3 words it will print e.g. "Hey there, how are you?" it prints, I think 100 words. But when I write sentences that contain less than 3 words, it works as it should. and I wonder if you would check what I have done wrong.
My question is how should I change/make it so it only prints one line instead of 100.
I am new to programming and English is not my mother tongue.
#include <stdio.h>
#include <string.h>
#define SIZE 100
int main(void)
{
char arr[SIZE];
char* p = NULL;
do {
int count = 0;
printf("Enter a sentence:");
fgets(arr, SIZE, stdin);
for (int i = 0; i < SIZE; i++) {
if (arr[i] == ' ') {
count++;
}
}
if (count < 3) {
printf("The sentence is to short!\n");
}
else {
count = 0;
for (int i = 0; i < SIZE; i++) {
if (arr[i] == ' ') {
count++;
}
if (count == 2) {
p= &arr[i + 2];
}
printf("%s\n", p);
}
}
return 0;
} while (1);
}
A few issues:
You always do the printf even if p is NULL, so you'll segfault
If we fixed that, you are not splitting the sentence into words, so you'll print the remaining part of the line
Once you start printing, you never stop.
Much better to split into words using strtok.
Here is the refactored code:
#include <stdio.h>
#include <string.h>
#define SIZE 100
int
main(void)
{
char arr[SIZE];
int count = 0;
printf("Enter a sentence:");
fgets(arr, SIZE, stdin);
char *bp = arr;
while (1) {
char *cp = strtok(bp," \n");
bp = NULL;
if (cp == NULL)
break;
if (++count == 2) {
printf("%s\n",cp);
break;
}
}
if (count < 2)
printf("The sentence is to short!\n");
return 0;
}
fgets(arr, SIZE, stdin);
for (int i = 0; i < SIZE; i++) {
SIZE is good for dimensioning the array and as a parameter to fgets() informing the function of the maximum size of the array. Once the input is returned, however, you only want to deal with the leading region of the buffer (up to the terminating '\0'); not the full length of the buffer.
Beyond that, the "flow control" is quite mixed up. Too much happening without a clear sequence of what is being checked and when things are being used (invoked).
The title, the question and the code make it unclear if you want to print everything after the skipped leading words, or just the next word after skipping.
strtok() has its place, but the string passed must be 'mutable' (meaning that strtok will replace some characters with '\0'; the original string buffer will be lost.) An advantage of strtok() is that several different separators can be specified, and one-or-more separators appearing together are dealt-with as if there were only one at that location.
To "fine-tune" this operation, and retain the original string buffer, here is a bit of code that only 'sniffs-at' the string buffer looking for single SPs separating "words". The final print statements show that the buffer remains unaffected. This can be useful when substrings of a string literal are to be retrieved.
#include <stdio.h>
#define SIZE 100
int main( void ) {
char arr[SIZE], *p = NULL;
int skip = 1; // skip one word
for( ;; ) {
printf( "Enter a sentence: ");
fgets( arr, SIZE, stdin );
p = arr;
while( skip >= 0 && (p = strchr( p, ' ' ) ) != NULL )
skip--, p++;
if( p && strchr( p, ' ' ) )
break;
puts( "The sentence is too short!" );
}
putchar( '\n' );
printf( "Rest of sentence: %s", p );
printf( "Next word only: " );
while( *p && *p != ' ' )
putchar( *p++ );
putchar( '\n' );
printf( "Whole sentence: %s", arr );
return 0;
}
Enter a sentence: /* pressed ENTER */
The sentence is too short!
Enter a sentence: the
The sentence is too short!
Enter a sentence: the quick
The sentence is too short!
Enter a sentence: the quick brown fox
Rest of sentence: quick brown fox
Next word only: quick
Whole sentence: the quick brown fox

Counting Characters and Strings n C

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

using isdigits , isalpha, and ispunct in C

I'm trying to identify the number of alphabets, number and punctuation by the user input , I got the No. of number but the alphabets and punctuation is incorrect!! .
i'm not sure why..
this is my code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char str[50];
int alphabet = 0 , number = 0, punct = 0;
printf("Enter your sentence: ");
fgets(str, sizeof(str),stdin);
for(int i=0 ; i<50; i++)
{
if(isalpha(str[i]) != 0)
{
alphabet++;
}
else if (isdigit(str[i]) != 0 ){
number++;
}
else if (ispunct(str[i]) != 0){
punct++;
}
}
printf("Your sentence contains:\n");
printf("Alphabets: %d",alphabet);
printf("\nDigits: %d",number);
printf("\nPunctuation: %d",punct);
return 0;
}
This loop
for(int i=0 ; i<50; i++)
is incorrect. The entered string can be less than the size of the character array str.
So instead use
for( size_t i = 0 ; str[i] != '\0'; i++ )
Take into account that the function fgets can append the new line character
\n' to the entered string. If you want to remove it before the loop then write
#include <string.h>
//…
str[strcspn( str, "\n" )] = '\0';
Also in if statements you should convert the given character to the type unsigned char. For example
if( isalpha( ( unsigned char )str[i] ) != 0)
or
if( isalpha( ( unsigned char )str[i] ) )
Otherwise in general without casting such a call can invoke undefined behavior if the code of a character is negative.
You have hardcoded the upper boundary of the loop: for(int i=0 ; i<50; i++), however can you guarantee your input is 49 characters long? If you cannot, then you will be reading garbage values past '\0' inserted by fgets. Either change the loop (for example): for(int i=0; i<50 && str[i]; i++) so that you only loop through to the end of the input.
Alternatively, zero-initialize the input buffer, i.e. char str[50] = {0};, I believe isalpha(), isdigit() and ispunct() all return false with a zero input, therefore not affecting your results.

Reversing String Only Using For Loop

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

C programming, segmentation fault core dump

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.

Resources