I need help about this exam.I need to reverse the input string.
int main(void)
{
char str[30];
int strlen; int i=0; int count=0;int temp;int j;
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
strlen=count;
printf("The length of the string:%d\n", strlen);
i=0;
j=strlen;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s",str);
return 0;
}
The problem is that at the end its not show me the string.
It shows me :
"Reverse string :"
and that is, no reverse string. Where is my mistake?
In your code you are doing
j=strlen;
j points to the last index of the string which will be '\0'
And later in the loop you set str[i]=str[j];
Therefore, the first index will be \0
Printing str will display nothing
In order to make the code correct set j=strlen - 1;
Try this:-
As In your code you are assigning j=strlen pointing to \0 or null character change it to j=strlen-1;
char str[30];
int strlen;int i=0;int count=0;int temp;int j;
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
strlen=count;
printf("The lenht of the string:%d\n",strlen);
i=0;
j=strlen-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s",str);
The problem is with the assignment j=strlen;'.
People will suggest you to change it toj=strlen - 1;`
But, I'll recommend to resolve at its root.
while(str[i]!='\0')
{
i++;
count++;
}
After this loop, count will hold value as the index which has a '\0' of the string. Here, you should decrement count and then assign it to strlen. That makes the code more understandable.
With this change, you'll also have to change
printf("The length of the string: %d\n", strlen);
to
printf("The length of the string: %d\n", strlen+1);
as it would print
The length of the string: 4
instead of 5 for "Hello" because of the decrement.
Additionally, strlen is a function once you include string.h header file in your code. To keep it portable, you should always use naming convention which won't have standard, common function names (such as strlen) as a variable name in your code.
A slightly better version (using purely your logic) than your existing code will use one variable less, and will look like this:
#include<stdio.h>
int main(void)
{
//char str[30] = "Hello";
char str[30] = { [0 ... 29] = 0 };
//int str_length = 0;
int i = 0, count = 0, j = 0;
char temp = 0; //This should be a char rather than an int
printf("Enter the string \n");
gets(str);
while(str[i]!='\0')
{
i++;
count++;
}
printf("The length of the string: %d\n", count);
if(count) count--;
//str_length = count;
i = 0;
j = count;
while(i < j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
printf("Reverse string :%s", str);
return 0;
}
Related
I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.
My first program. I would like it if the user enters a word made of letters and then it uses my loop function to output mixed up even and odd characters. Currently I cannot get it to compile. Bonus points if someone can show me how to loop the users input so after it asks the size to make the array, it prompts the user that many times for an "element" or word so that the function can scramble it and output it.
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
char str[size];
printf("How many elements?");
scanf("%d", &size);
printf("Please type an element: ");
//Get input from user
str[0] = scanf("%s", str);
transform(str);
printf("Please type another element: ");
//Get another input from user
str[1] = scanf("%s", str);
transform(str);
//This is the loop function that I programmed
char transform(char str[]);
{
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 == 0)
{
printf("%c", str[i]);
}
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 != 0)
{
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
}
#include <stdlib.h>
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
printf("How many elements?");
scanf("%d", &size);
for (int i = 0; i < size; ++i)
{
printf("Please type an element: ");
char str[2048]; //declare a wide buffer to be able to store lots of chars
scanf("%s", str);
transform(str);
}
return 0;
} //end your main here, by putting closing brace
char transform(char str[]) //define transform without semicolon, and outside of main
{ //This is the loop function that I programmed
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 == 0)
printf("%c", str[i]);
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 != 0)
printf("%c", str[i]);
}
printf("\n");
return 0;
}
This is the code I am not able to fix it. It works fine if 5 or more characters are used but using less than 4 characters breaks it.
#include <stdio.h>
void main()
{
char str[1000], rev[1000];
int i, j, count = 0;
printf("Enter the string :");
scanf("%s", str);
printf("\nString Before Reverse: %s", str);
while (str[count] != '\0')
{
count++;
}
j = count-1 ;
for (i = 0; i<count; i++)
{
rev[i] = str[j];
j--;
}
printf("\nString After Reverse: %s", rev);
}
Your have to null terminate your rev string like:
rev[count] = '\0';
Also, please make your code more readable.
I am very confused to create a function which will print a string and ask user to enter two numbers and then function will replace those number of words with one another.
I have added the image below as sample.
enter image description here
This is my homework, I have created other 3 functions, but don't really get this one.
Could somebody please help me how can I convert the words into numbers and then replace those number of words with one another.
This is my program it can break the string into words but how can i replace position of words.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
Seems to me that you are doing pretty good so far (your code can't handle comma but you can add that later). So let's assume that your newString actually contains the individual words.
So your next step is to construct a new string str2 from the individual words you have in newString. While you do that you can simply swap the two words of interest. To build the new string the strcat function could be helpful.
The code below is not fully correct but it may give you some ideas for getting on with your homework:
int lowest_index_to_swap = some_number
int highest_index_to_swap = some_higher_number
char str2[100] = "";
for (i=0; i<number_of_words_found; ++i)
{
if (i == lowest_index_to_swap)
strcat(str2, newString[highest_index_to_swap];
else if (i == highest_index_to_swap)
strcat(str2, newString[lowest_index_to_swap];
else
strcat(str2, newString[i];
strcat(str2, " ";
}
Here is code snippet what I tried in my local server based on your input in image.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 100
#define WORDLEN 20
int main() {
int place_1, place_2, count = 0, i, k =0;
char str[] = "Hi, welcome to C programming";
char **words = (char **)malloc(sizeof(char *)*SIZE);
if(!words){
printf("malloc of words failed!\n");
exit(1);
}
char *temp = (char *)malloc(sizeof(char)*WORDLEN);
if(!temp){
printf("malloc of temp failed!\n");
exit(1);
}
for(i = 0; str[i] != '\0'; count++){
words[count] = (char *)malloc(sizeof(char)*WORDLEN);
if(!words[count]){
printf("malloc of words[%d] failed!\n", count);
exit(1);
}
sscanf(str+i, "%s", words[count]);
i += 1+strlen(words[count]);
printf("%d %s %d\n", count, words[count], i);
}
printf("Enter the word places to replace: ");
if(scanf("%d %d", &place_1, &place_2) < 2){
printf("scanf failed!\n");
exit(1);
}
temp = words[place_1 - 1];
words[place_1 - 1] = words[place_2 - 1];
words[place_2 - 1] = temp;
for(i = 0; i < count; i++){
sprintf(str+k, "%s ", words[i]);
k += 1+strlen(words[i]);
}
printf("str: %s\n", str);
free(temp);
for(i = 0; i < count; i++){
free(words[i]);
}
free(words);
}
Hope it helps.
I need to compare tokens.
I need to know two tokens which are equal.
This is my code. And something is going wrong when comparing- compilator just crashes.
Can you help me to find error?
int main()
{
int i=0;
char* words[200];
char text[200];
printf("Enter one sentence \n ");
gets(text);
char *word = strtok(text, " ");
while(word!=0)
{
words[i++] = strdup(word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}
for (k=0; k<199; k++)
{
for (j=k+1; j<200; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("Equal words are %s",words);
}
else
{
printf("In this sentence aren't equal words");
}
}
}
getch();
return 0;
In your for loops you iterate until 200, not until the max number of entered words (i) is reached.
There is no guarantee which value the elements of an uninitialized array will have at runtime. They might be 0, but also might be any other random numbers. Which means, that doing strcmp with any array element beyond the number of entered words will result in undefined behavior.
Do your nested for-loop like this:
for (k=0; k < i-1; k++)
{
for (j=k+1; j < i; j++)
{
...
}
}
I realize this is an old question, but I found #elgonzo's answer helpful and was able to get your program to compile after a few other changes. I added the libraries, added \n to the print statements, and initialized the variables k and j which may have been part of your problem.
Here's my version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i=0, k=0, j=0;
char* words[200];
char text[200];
printf("Enter one sentence \n ");
gets(text);
char *word = strtok(text, " ");
while(word!=0)
{
words[i++] = strdup(word);
printf("[%s]\n", word);
word=strtok(NULL, " ,.!?");
}
for (k=0; k < i-1; k++)
{
for (j=k+1; j < i; j++)
{
if (strcmp(words[k],words[j])==0)
{
printf("Equal words are %s\n", *words);
}
else
{
printf("In this sentence aren't equal words\n");
}
}
}
return 0;
}