c programing Write a program to read in a string from the ke
c programing
Solution
#include<stdio.h>
void String_backwards(char str[],int count)
{
//these variables are used for loop while swaping characters of String str
int i, j;
// temp will store character of String str while swapping
char temp;
/*
* Below we swap the first character of the string str with the last character
* of the String str
* str[i] start from first char, as i value is 0 and str[j] start from last char, i.e., count,
* str[i] and str[j] values are swapped using temp variable
* and then we increase i by 1 and decrease j by 1.
* This process run until the condition i < j becomes false.
*/
for(i=0, j = count; i < j; i++, j--)
{
temp = str[i]; // temp will have ith character of string str, i.e., str[i]
str[i] = str[j]; // str[i] and str[j] will be swapped
str[j] = temp; // str[i] will get the character stored in temp
}
//Here we run a for loop to traverse the string of characters
//and display the String character by character
for (i = 0; i < count ; i++){
printf(\"%c\", str[i]); //Printing each character
}
}
int main(void)
{
// This is an array of type char to hold the string entered by user. Size is 50, which can be modified as per use
char str[50];
// This variable is of type integer. This variable will be used to count the number of characters of the String entered by user
int count;
//Asking the user to enter the String
printf(\"Please enter the String that is to be displayed backwards\ \");
//Running a for loop to read character by character of String using getchar() method
//count is initially set to 0 , which will increase on each character read
for(count=0; (str[count]=getchar()) != \'\ \'; ++count);
//We are calling String_backwards function to do the display the string backwards
//str and count are two variables passed for the working of the function
String_backwards(str, count);
return 0;
}
The above solution uses for loops and swapping method. Same problem can be solved using recursion and pointers. I would suggest to try the other techniques also.
In case of any query related to the solution, feel free to ontact.
Thanks.

